1 struct Edge { 2 int v, w; 3 int next; 4 }edge[250*250]; 5 int head[50], tot; 6 void addedge(int u, int v, int w) { 7 edge[tot].v = v; 8 edge[tot].w = w; 9 edge[tot].next = head[u]; 10 head[u] = tot++; 11 } 12 int lvl[305]; 13 bool bfs(int s, int t) { 14 lvl[s] = 0; 15 queue<int> Q; 16 Q.push(s); 17 while(!Q.empty()) { 18 int tmp = Q.front(); 19 Q.pop(); 20 if(tmp == t) return true; 21 for(int i = head[tmp]; i+1; i = edge[i].next) { 22 int v = edge[i].v; 23 int w = edge[i].w; 24 if(!lvl[v] && w) { 25 Q.push(v); 26 lvl[v] = lvl[tmp] + 1; 27 } 28 } 29 } 30 return false; 31 } 32 int dfs(int now, int t, int F) { 33 if(now == t) return F; 34 int ret = 0, f; 35 for(int i = head[now]; i+1; i = edge[i].next) { 36 int v = edge[i].v; 37 int w = edge[i].w; 38 if(w && lvl[v] == lvl[now] + 1) { 39 f = dfs(v, t, min(F-ret, w)); 40 edge[i].w -= f; 41 edge[i^1].w += f; 42 ret += f; 43 if(ret == F) return ret; 44 } 45 } 46 return ret; 47 } 48 int dinic(int s, int t) { 49 int ans = 0; 50 while(bfs(s, t)) ans += dfs(s, t, INF); 51 return ans; 52 }
原文:http://www.cnblogs.com/mitrenick/p/4440083.html