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