Dinic算法模板
详解:http://blog.csdn.net/wall_f/article/details/8207595
算法时间复杂度:O(E * V * V)
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #include <vector> 5 using namespace std; 6 #define N 105 7 #define M 1010 8 #define INF 0x3f3f3f3f 9 10 struct Edge { 11 int u, v, cap; 12 Edge () {} 13 Edge (int u, int v, int cap) : u (u), v (v), cap (cap) {} 14 }edge[N*N]; 15 vector<int> G[N]; 16 int S, T, cur[N], dis[N], tot; 17 18 void Addedge(int u, int v, int cap) { 19 G[u].push_back(tot); 20 edge[tot++] = Edge(u, v, cap); 21 G[v].push_back(tot); 22 edge[tot++] = Edge(v, u, 0); 23 } 24 25 int BFS() { // 找层次图 26 queue<int> que; 27 while(!que.empty()) que.pop(); 28 memset(dis, INF, sizeof(dis)); 29 que.push(S); 30 dis[S] = 0; 31 while(!que.empty()) { 32 int u = que.front(); que.pop(); 33 for(int i = 0; i < G[u].size(); i++) { 34 Edge &e = edge[G[u][i]]; 35 if(dis[e.v] == INF && e.cap > 0) { 36 dis[e.v] = dis[u] + 1; 37 que.push(e.v); 38 } 39 } 40 } 41 return dis[T] != INF; 42 } 43 44 int DFS(int u, int maxflow) { // 找增广路 45 if(u == T) return maxflow; // 46 for(int i = cur[u]; i < G[u].size(); i++) { 47 cur[u] = i; // 当前弧优化 48 Edge &e = edge[G[u][i]]; 49 if(dis[e.v] == dis[u] + 1 && e.cap > 0) { 50 int flow = DFS(e.v, min(e.cap, maxflow)); // 找到增广路上最小的流量增量 51 if(flow) { 52 e.cap -= flow; 53 edge[G[u][i]^1].cap += flow; 54 return flow; 55 } 56 } 57 } 58 return 0; // 找不到增广路 59 } 60 61 int Dinic() { 62 int ans = 0; 63 while(BFS()) { 64 int flow; 65 memset(cur, 0, sizeof(cur)); 66 while(flow = DFS(S, INF)) ans += flow; 67 } 68 return ans; 69 }