/* HDU3549网络最大流Dinic 题意:给定一个图,找出加权有向图的最大流 输入的第一行包含一个整数T,表示测试用例的数目。 对于每一个测试案例,第一行包含两个整数n和m,表示图中顶点和边数。 接下来的m行,每行包含三个整数x,y和z,表示从x到y的一条边的容量是z 对于每一组测试样例,输出从1到n的最大流量。 Sample Input 2 3 2 1 2 1 2 3 1 3 3 1 2 1 2 3 1 1 3 1 Sample Output Case 1: 1 Case 2: 2 */ #include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #include <vector> #include <queue> #define maxn 10010 #define INF 0x3f3f3f3f using namespace std; struct Edge { int from,to,cap,flow; }; bool operator < (const Edge& a, const Edge& b) { return a.from < b.from || (a.from == b.from && a.to < b.to); } struct Dinic { int n,m,s,t; vector<Edge>edges; vector<int>G[maxn]; bool vis[maxn]; int d[maxn]; int cur[maxn]; void Init(int n) { this->n = n; for(int i = 0; i < n; i ++) G[i].clear(); edges.clear(); } void Addedge(int from,int to,int cap) { edges.push_back((Edge) { from,to,cap,0 }); edges.push_back((Edge) { to,from,0,0 }); m = edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool BFS() { memset(vis,0,sizeof(vis)); queue<int>Q; Q.push(s); d[s] = 0; vis[s] = 1; while(!Q.empty()) { int x = Q.front(); Q.pop(); for(int i = 0; i < G[x].size(); i ++) { Edge& e = edges[G[x][i]]; if(!vis[e.to] && e.cap > e.flow) { vis[e.to] = 1; d[e.to] = d[x] + 1; Q.push(e.to); } } } return vis[t]; } int DFS(int x,int a) { if(x == t || a == 0) return a; int flow = 0,f; for(int& i = cur[x]; i < G[x].size(); i ++) { Edge& e = edges[G[x][i]]; if(d[x] + 1 == d[e.to] && (f = DFS(e.to,min(a,e.cap-e.flow)))>0) { e.flow += f; edges[G[x][i]^1].flow -= f; flow += f; a -= f; if(a == 0) break; } } return flow; } int Maxflow(int s, int t) { this->s = s; this->t = t; int flow = 0; while(BFS()) { memset(cur, 0, sizeof(cur)); flow += DFS(s, INF); } return flow; } }; Dinic g; int main() { int num = 0; int T,n,m,x,y,z; scanf("%d",&T); while(T --) { scanf("%d%d",&n,&m); g.Init(n); for(int i = 0; i < m; i ++) { scanf("%d%d%d",&x,&y,&z); g.Addedge(x - 1,y - 1,z); } int flow = g.Maxflow(0,n-1); printf("Case %d: %d\n",++num,flow); } return 0; }
时间: 2024-10-13 08:00:30