POJ_1637
前些日子被各种网络流狂虐一番,现在准备好好搞一搞网络流的题目了,这题果断又被虐了,推荐一篇Edelweiss的网络流建模总结:http://wenku.baidu.com/view/0ad00abec77da26925c5b01c.html。
#include<stdio.h> #include<string.h> #include<stdlib.h> #define MAXD 210 #define MAXM 2410 #define INF 0x3f3f3f3f int S, T, N, M, first[MAXD], e, next[MAXM], v[MAXM], flow[MAXM]; int indgr[MAXD], outdgr[MAXD], work[MAXD], q[MAXD], d[MAXD]; void add(int x, int y, int z) { v[e] = y, flow[e] = z; next[e] = first[x], first[x] = e ++; } void init() { int i, x, y, k; scanf("%d%d", &N, &M); memset(first, -1, sizeof(first)); e = 0; memset(indgr, 0, sizeof(indgr)); memset(outdgr, 0, sizeof(outdgr)); for(i = 0; i < M; i ++) { scanf("%d%d%d", &x, &y, &k); ++ outdgr[x], ++ indgr[y]; if(k == 0) add(x, y, 1), add(y, x, 0); } } int bfs() { int i, j, k, rear = 0; memset(d, -1, sizeof(d[0]) * (N + 2)); d[S] = 0, q[rear ++] = S; for(i = 0; i < rear; i ++) for(j = first[q[i]]; j != -1; j = next[j]) if(flow[j] && d[v[j]] == -1) { d[v[j]] = d[q[i]] + 1; if(v[j] == T) return 1; q[rear ++] = v[j]; } return 0; } int dfs(int cur, int a) { if(cur == T) return a; int t; for(int &i = work[cur]; i != -1; i = next[i]) if(flow[i] && d[v[i]] == d[cur] + 1) if(t = dfs(v[i], a < flow[i] ? a : flow[i])) { flow[i] -= t, flow[i ^ 1] += t; return t; } return 0; } int dinic() { int t, ans = 0; while(bfs()) { memcpy(work, first, sizeof(first[0]) * (N + 2)); while(t = dfs(S, INF)) ans += t; } return ans; } void solve() { int i, j, k, tot = 0; S = 0, T = N + 1; for(i = 1; i <= N; i ++) { k = abs(indgr[i] - outdgr[i]); if(k & 1) { printf("impossible\n"); return ; } k >>= 1; if(indgr[i] > outdgr[i]) add(i, T, k), add(T, i, 0); else if(indgr[i] < outdgr[i]) add(S, i, k), add(T, i, 0); tot += k; } if(dinic() == tot >> 1) printf("possible\n"); else printf("impossible\n"); } int main() { int t; scanf("%d", &t); while(t --) { init(); solve(); } return 0; }