很裸的模版题,就是敲起来稍微麻烦一点。
#include<bits/stdc++.h> using namespace std; struct Edge { int v,cap; }; const int maxn = 101; vector<Edge> E; vector<int> G[maxn]; #define PB push_back void AddEdge(int u,int v,int c) { G[u].PB(E.size()); E.PB({v,c}); G[v].PB(E.size()); E.PB({u,0}); } int S,T; bool vis[maxn]; int d[maxn]; bool bfs() { memset(vis,0,sizeof(vis)); queue<int> q; q.push(S); d[S] = 0; vis[S] = true; while(q.size()){ int u = q.front(); q.pop(); for(int i = 0; i < G[u].size(); i++){ Edge &e = E[G[u][i]]; if(!vis[e.v] && e.cap>0){ vis[e.v] = true; d[e.v] = d[u]+1; q.push(e.v); } } } return vis[T]; } int cur[maxn]; int dfs(int u,int a) { if(u == T||!a) return a; int flow = 0,f; for(int &i = cur[u]; i < G[u].size(); i++){ Edge &e = E[G[u][i]]; if(d[e.v] == d[u]+1 && (f = dfs(e.v,min(e.cap,a)))>0){ flow += f; e.cap -= f; E[G[u][i]^1].cap += f; a -= f; if(!a) break; } } return flow; } const int INF = 0x3f3f3f3f; int MaxFlow() { int flow = 0; while(bfs()){ memset(cur,0,sizeof(cur)); flow += dfs(S,INF); } return flow; } int cap[maxn][maxn]; int main() { //freopen("in.txt","r",stdin); int n,kas = 0; while(scanf("%d",&n),n){ for(int i = 1; i <= n; i++) G[i].clear(); E.clear(); memset(cap,0,sizeof(cap)); int m; scanf("%d%d%d",&S,&T,&m); while(m--){ int u,v,c; scanf("%d%d%d",&u,&v,&c); cap[u][v] += c; cap[v][u] = cap[u][v]; } for(int i = 1; i <= n; i++) for(int j = i+1; j <= n; j++) if(cap[i][j]>0){ AddEdge(i,j,cap[i][j]); AddEdge(j,i,cap[i][j]); } printf("Network %d\nThe bandwidth is %d.\n\n",++kas,MaxFlow()); } return 0; }
时间: 2024-10-08 10:17:45