最大流

来源:互联网 发布:linux less 显示行号 编辑:程序博客网 时间:2024/04/27 18:36
 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 
 5 const int N = 210;
 6 const int INF = 0x7FFFFFFF;
 7 int n,m,map[N][N],path[N],flow[N],start,end;
 8 queue<int> q;
 9 
10 int bfs(){
11     int i,t;
12     while(!q.empty()) q.pop();
13     memset(path,-1,sizeof(path));
14     path[start]=0,flow[start]=INF;
15     q.push(start);
16     while(!q.empty()){
17         t=q.front();
18         q.pop();
19         if(t==end) break;
20         for(i=1;i<=m;i++){
21             if(i!=start && path[i]==-1 && map[t][i]){
22                 flow[i]=flow[t]<map[t][i]?flow[t]:map[t][i];
23                 q.push(i);
24                 path[i]=t;
25             }
26         }
27     }
28     if(path[end]==-1return -1;
29     return flow[m];                   //一次遍历之后的流量增量
30 }
31 int Edmonds_Karp(){
32     int max_flow=0,step,now,pre;
33     while((step=bfs())!=-1){          //找不到增路径时退出
34         max_flow+=step;
35         now=end;
36         while(now!=start){
37             pre=path[now];
38             map[pre][now]-=step;      //更新正向边的实际容量
39             map[now][pre]+=step;      //添加反向边
40             now=pre;
41         }
42     }
43     return max_flow;
44 }
45 int main(){
46     int i,u,v,cost;
47     while(scanf("%d %d",&n,&m)!=EOF){
48         memset(map,0,sizeof(map));
49         for(i=0;i<n;i++){
50             scanf("%d %d %d",&u,&v,&cost);
51             map[u][v]+=cost;           //not just only one input
52         }
53         start=1,end=m;
54         printf("%d\n",Edmonds_Karp());
55     }
56     return 0;
57 }
58
原创粉丝点击