网络流-Edmonds-Karp算法

网络流的Edmonds-Karp算法代码

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<list>
 4 #include<queue>
 5 #include<climits>
 6 using namespace std;
 7 int n,m,s,t;
 8 int map[1001][1001];//残存网络
 9 int store[1001][1001]; //输入网络
10 int c[1001][1001];//流网络
11 struct datatype{
12     list<int>path;
13     int pos;
14 };
15 queue<datatype> q;
16 bool vis[1001];
17 void cal(datatype x){
18     list<int>::iterator it;
19     int f=INT_MAX;
20     int last=*x.path.begin();
21     it=x.path.begin();
22     it++;
23     for(it;it!=x.path.end();it++){
24         f=min(f,map[last][*it]);
25         last=*it;
26     }
27     last=*x.path.begin();
28     it=x.path.begin();
29     it++;
30     for(it;it!=x.path.end();it++){
31         if(store[last][*it])
32             c[last][*it]+=f;
33         else
34             c[*it][last]-=f;
35         map[last][*it]-=f;
36         map[*it][last]+=f;
37         last=*it;
38     }
39     return;
40 }
41 bool get_path(datatype start){
42     q.push(start);
43     while(!q.empty()){
44         datatype now=q.front();
45         if(now.pos==t){
46             cal(now);
47             return true;
48         }
49         for(int i=1;i<=n;i++)
50             vis[i]=false;
51         list<int>::iterator it;
52         for(it=now.path.begin();it!=now.path.end();it++)
53             vis[*it]=true;
54         for(int i=1;i<=n;i++)
55             if(!vis[i]&&map[now.pos][i]){
56                 datatype tmp;
57                 tmp.path=now.path;
58                 tmp.path.push_back(i);
59                 tmp.pos=i;
60                 q.push(tmp);
61             }
62         q.pop();
63     }
64     return false;
65 }
66 int main(){
67     cin>>n>>m;
68     for(int i=1;i<=n;i++)
69         for(int j=1;j<=n;j++){
70             map[i][j]=0;
71             c[i][j]=0;
72         }
73     for(int i=1;i<=m;i++){
74         int x,y,z;
75         cin>>x>>y>>z;
76         map[x][y]=z;
77     }
78     for(int i=1;i<=n;i++)
79         for(int j=1;j<=n;j++)
80             store[i][j]=map[i][j];
81     cin>>s>>t;
82     datatype start;
83     start.path.clear();
84     start.path.push_back(s);
85     start.pos=s;
86     while(get_path(start))
87         while(!q.empty())
88             q.pop();
89     int res=0;
90     for(int i=1;i<=n;i++)
91         if(c[i][t]>0)
92             res+=c[i][t];
93     cout<<res<<endl;
94     return 0;
95 }

猜你喜欢

转载自www.cnblogs.com/shao0099876/p/9335787.html