#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 10000 + 5;
const int INF = 1e8;
struct Edge{
int from,to,cap,flow;
Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f) {}
};
struct EdmondsKarp{
int n,m;
vector<Edge> edges; //边数的两倍
vector<int> G[maxn];
int a[maxn]; //当起点到i的可改进量
int p[maxn]; //最短路上p的入弧编号
void init(int 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,cap,0));//反向弧
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);//G[i][j]表示节点i的第j条边在e数组的序号
}
int Maxflow(int s,int t){
int flow=0;
for(;;){
memset(a,0,sizeof(a));
queue<int> Q;
Q.push(s);
a[s]=INF;
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(!a[e.to]&&e.cap>e.flow){
p[e.to] = G[x][i];//p数组相当于记录了 e.to的入弧,卧槽是不是很啰嗦,但是我自己理解了
a[e.to] = min(a[x],e.cap-e.flow);//找到这一条路上残量最小值
Q.push(e.to);
}
}
if(a[t]) break;
}
if(!a[t]) break;
for(int u=t;u!=s;u=edges[p[u] ].from){
edges[p[u] ].flow += a[t];
edges[p[u]^1 ].flow -= a[t];
}
flow += a[t];
}
return flow;
}
};
int main()
{
//freopen("in.txt", "r", stdin);
int kase = 0; int n;
while(~scanf("%d", &n) && n) {
EdmondsKarp ek;
ek.init(n * 4 + 10);
int s, t, m;
scanf("%d%d%d", &s, &t, &m);
int u, v, cap;
for(int i = 0; i < m; i++) {
scanf("%d%d%d", &u, &v, &cap);
ek.AddEdge(u, v, cap);
}
printf("Network %d\n", ++kase);
printf("The bandwidth is %d.\n\n", ek.Maxflow(s, t));
}
return 0;
}
uva820(最大流)
最新推荐文章于 2019-07-09 15:17:50 发布