pku1273 Drainage Ditches
http://poj.org/problem?id=1273
网络流,Dinic
1 #include <stdio.h> 2 #include <string.h> 3 #include <queue> 4 5 using namespace std; 6 7 const int inf = 1<<30; 8 const int maxn = 202, maxm = 202; 9 10 struct Edge 11 { 12 int v, f, nxt; 13 }; 14 15 int n, src, sink; 16 int g[maxn + 10]; 17 int nume; 18 Edge e[maxm*2 + 10]; 19 20 void addedge(int u, int v, int c) 21 { 22 e[++nume].v = v; 23 e[nume].f = c; 24 e[nume].nxt = g[u]; 25 g[u] = nume; 26 e[++nume].v = u; 27 e[nume].nxt = g[v]; 28 g[v] = nume; 29 } 30 31 32 queue<int> que; 33 bool vis[maxn + 10]; 34 int dist[maxn + 10]; 35 36 void bfs() 37 { 38 memset(dist, 0, sizeof(dist)); 39 while(!que.empty()) 40 { 41 que.pop(); 42 } 43 vis[src] = true; 44 que.push(src); 45 while(!que.empty()) 46 { 47 int u = que.front(); 48 que.pop(); 49 for(int i=g[u]; i; i=e[i].nxt) 50 { 51 if(e[i].f && !vis[e[i].v]) 52 { 53 que.push(e[i].v); 54 dist[e[i].v] = dist[u] + 1; 55 vis[e[i].v] = true; 56 } 57 } 58 } 59 } 60 61 int dfs(int u, int delta) 62 { 63 if(u == sink) 64 { 65 return delta; 66 } 67 else 68 { 69 int ret = 0; 70 for(int i=g[u]; delta && i; i=e[i].nxt) 71 { 72 if(e[i].f && dist[e[i].v] == dist[u] + 1) 73 { 74 int dd = dfs(e[i].v, min(e[i].f, delta)); 75 e[i].f -= dd; 76 e[i ^ 1].f += dd; 77 delta -= dd; 78 ret += dd; 79 } 80 } 81 return ret; 82 } 83 } 84 85 int maxflow() 86 { 87 int ret = 0; 88 while(true) 89 { 90 memset(vis, 0, sizeof(vis)); 91 bfs(); 92 if(!vis[sink]) 93 { 94 return ret; 95 } 96 ret += dfs(src, inf); 97 } 98 } 99 100 101 int main() 102 { 103 int n, m; 104 int i, x, y, z; 105 while(~scanf("%d%d", &m, &n)) 106 { 107 memset(g, 0, sizeof(g)); 108 nume = 1; 109 src = 1; 110 sink = n; 111 for(i=1; i<=m; i++) 112 { 113 scanf("%d%d%d", &x, &y, &z); 114 addedge(x, y, z); 115 } 116 x = maxflow(); 117 printf("%d\n", x); 118 } 119 return 0; 120 }