喜欢dinic算法,清晰,简洁,高效,优雅。
uva820.
#include <iostream> #include <cstdio> #include <string> #include <vector> #include <cstring> #include <utility> #include <algorithm> using namespace std; const int Maxn = 105; const int Maxm = 30005; const int inf = 0x1fffffff; int n, m, s, t, queue[Maxn], lab[Maxn]; int tot, h[Maxn], nxt[Maxm<<1], v[Maxm<<1], res[Maxm<<1]; void addEdge(int a, int b, int c) { v[tot] = b; res[tot] = c; nxt[tot] = h[a]; h[a] = tot++; v[tot] = a; res[tot] = 0; nxt[tot] = h[b]; h[b] = tot++; } bool bfs(int s, int t) { int head, tail, u; memset(lab, -1, sizeof(lab)); lab[s] = head = tail =0; queue[0] = s; while(head <= tail) { u = queue[head++]; for(int i = h[u]; i != -1; i = nxt[i]) if(res[i]>0 && lab[v[i]]==-1) { lab[v[i]] = lab[u] +1; queue[++tail] = v[i]; } } if(lab[t] != -1) return true; else return false; } int dinicDfs(int delta, int u) { int sum =0, tmp; if(u == t) return delta; else { for(int i = h[u]; i != -1; i = nxt[i]) if(lab[v[i]]==lab[u]+1 && res[i]>0) { tmp = dinicDfs(min(delta, res[i]), v[i]); sum += tmp; delta -= tmp; res[i] -= tmp; res[i^1] += tmp; } return sum; } } int maxFlow(int s, int t) { int ans =0; while(bfs(s, t)) ans += dinicDfs(inf, s); return ans; } int main() { int a, b, c, Case = 0; freopen("data.in", "r", stdin); while(scanf("%d", &n) != EOF) { if(n == 0) break; tot = 0; memset(h, -1, sizeof(h)); scanf("%d%d%d", &s, &t, &m); for(int i = 0; i < m; i++) { scanf("%d%d%d", &a, &b, &c); addEdge(a, b, c); addEdge(b, a, c); } int ans = maxFlow(s, t); printf("Network %d\n", ++Case); printf("The bandwidth is %d.\n\n", ans); } return 0; }