uva563(最大流)

题目的意思就是一张网中,有几个银行,有个小偷要去偷,偷完要走到边缘的点.问能不能每个银行都偷过去,并且不能重复走边和点.

首先要把这题理解为网络流.

把银行的点,当做源点.

把边缘的点当做汇点.

然后把每个点能走上下左右连起来,容量为1.

注意的是这题必须拆点,因为每个点容量为一.

关于多源点,多汇点,还有拆点,可以参考这道模板题 http://blog.csdn.net/yeyeyeguoguo/article/details/41090471

因为这题建全图会超时,所以要用邻接表.


AC代码:


#include
#include
#include
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 55 * 55 * 2;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int cap[N * 10];
int flow[N * 10];
int p[N];
int a[N];
int u[N * 10];
int v[N * 10];
int first[N];
int nex[N * 10];
int e;
int r,c,n,f;
int ek(int t) {  
    queue q;  
    memset(flow , 0 ,sizeof(flow));  
    f = 0;  
    while(1) {  
        memset(a, 0 ,sizeof(a));  
		memset(p , -1 ,sizeof(p));
        a[0] = INF;  
        q.push(0);  
        while(!q.empty()) {  
            int k = q.front() ;  
            q.pop();  
            for (int w = first[k] ; w != -1; w = nex[w]) {
                if (!a[v[w]] && cap[w] - flow[w]  > 0) {
                    p[v[w]] = w;
                    q.push(v[w]);  
                    a[v[w]] = a[u[w]] < cap[w] - flow[w] ? a[u[w]] : cap[w] - flow[w];  
                }  
            }  
        }  
        if (a[t] == 0)  
            break;  
        for (int w = p[t] ; w != -1 ;w = p[u[w]]) {  
            flow[w] += a[t];  
            flow[w ^ 1] -= a[t];  
        }  
        f += a[t];  
    }  
    return f;  
}  
void add(int i , int j) {
	u[e] = i;
	v[e] = j;
	cap[e] = 1;
	nex[e] = first[u[e]];
	first[u[e]] = e;
	e++;
	u[e] = j;
	v[e] = i;
	cap[e] = 0;
	nex[e] = first[u[e]];
	first[u[e]] = e;
	e++;
}
int main() {
	int t;
	scanf("%d",&t);
	while (t--) {
		e = 0;
		memset(first , -1 , sizeof(first));
		scanf("%d%d%d",&r,&c,&n);
		int m = r * c;
		for (int i = 1 ; i <= m ;i++) {
			add(i ,i + m);
		}
		int d;
		for (int i = 1 ; i <= r ;i++) {
			for (int j = 1 ; j <= c ;j++) {
				for (int k = 0 ; k < 4 ;k++) {
					int x = i + dx[k];
					int y = j + dy[k];
					if (x >= 1 && x <= r && y >= 1 && y <= c) {
						add((i - 1) * c + j + m, (x - 1) * c + y);
					}
					else
						add((i - 1) * c + j + m, 2 * m + 1);
				}
			}
		}
		int g,b;
		for (int i = 0 ; i < n;i++) {
			scanf("%d%d",&g,&b);
			add(0 , (g - 1) * c + b);
		}
		int res = ek(2 * m + 1);
//		printf("%d\n",res);
		if (res == n)
			printf("possible\n");
		else
			printf("not possible\n");
	}
}




你可能感兴趣的:(图论)