http://acm.hdu.edu.cn/showproblem.php?pid=1532
求最大的流量,用dinic算法就好。
1 // Rujia Liu 2 // 因为图较大,所以采用Dinic而不是EdmondsKarp 3 // 得益于接口一致性,读者无须理解Dinic就能使用它。 4 #include<cstdio> 5 #include<cstring> 6 #include<queue> 7 #include<algorithm> 8 using namespace std; 9 10 const int maxn = 50*50+10; 11 12 const int INF = 1000000000; 13 14 struct Edge 15 { 16 int from, to, cap, flow; 17 }; 18 19 bool operator < (const Edge& a, const Edge& b) 20 { 21 return a.from < b.from || (a.from == b.from && a.to < b.to); 22 } 23 24 struct Dinic 25 { 26 int n, m, s, t; 27 vector<Edge> edges; // 边数的两倍 28 vector<int> G[maxn]; // 邻接表,G[i][j]表示结点i的第j条边在e数组中的序号 29 bool vis[maxn]; // BFS使用 30 int d[maxn]; // 从起点到i的距离 31 int cur[maxn]; // 当前弧指针 32 33 void init(int n) 34 { 35 for(int i = 0; i < n; i++) G[i].clear(); 36 edges.clear(); 37 } 38 39 void AddEdge(int from, int to, int cap) 40 { 41 edges.push_back((Edge){from, to, cap, 0}); 42 edges.push_back((Edge){to, from, 0, 0}); 43 m = edges.size(); 44 G[from].push_back(m-2); 45 G[to].push_back(m-1); 46 } 47 48 bool BFS() 49 { 50 memset(vis, 0, sizeof(vis)); 51 queue<int> Q; 52 Q.push(s); 53 vis[s] = 1; 54 d[s] = 0; 55 while(!Q.empty()) 56 { 57 int x = Q.front(); Q.pop(); 58 for(int i = 0; i < G[x].size(); i++) 59 { 60 Edge& e = edges[G[x][i]]; 61 if(!vis[e.to] && e.cap > e.flow) 62 { 63 vis[e.to] = 1; 64 d[e.to] = d[x] + 1; 65 Q.push(e.to); 66 } 67 } 68 } 69 return vis[t]; 70 } 71 72 int DFS(int x, int a) 73 { 74 if(x == t || a == 0) return a; 75 int flow = 0, f; 76 for(int& i = cur[x]; i < G[x].size(); i++) 77 { 78 Edge& e = edges[G[x][i]]; 79 if(d[x] + 1 == d[e.to] && (f = DFS(e.to, min(a, e.cap-e.flow))) > 0) 80 { 81 e.flow += f; 82 edges[G[x][i]^1].flow -= f; 83 flow += f; 84 a -= f; 85 if(a == 0) break; 86 } 87 } 88 return flow; 89 } 90 91 int Maxflow(int s, int t) 92 { 93 this->s = s; this->t = t; 94 int flow = 0; 95 while(BFS()) 96 { 97 memset(cur, 0, sizeof(cur)); 98 flow += DFS(s, INF); 99 } 100 return flow; 101 } 102 }; 103 104 Dinic g; 105 106 int main() 107 { 108 // freopen("a.txt","r",stdin); 109 int n,m,a,b,c; 110 while(~scanf("%d%d",&m,&n)) 111 { 112 g.init(n); 113 for(int i=0;i<m;i++) 114 { 115 scanf("%d%d%d",&a,&b,&c); 116 g.AddEdge(a,b,c); 117 } 118 printf("%d\n",g.Maxflow(1, n)); 119 } 120 return 0; 121 }
时间: 2024-10-27 06:51:36