最大流模板 Ford-Fulkerson and Dinic
自己码的哟~
Ford-Fulkerson:
算法:
用cup[][]记录流量;
一开始就用初始的图做残流网络
用BFS找到一条最短的从起点到终点的路径,并用a[]记录且标记这条路径上的最小流量
更新残流网络图,正向的减去最小流量,反向的加上最小流量;
累加最小流量做总和;
循环以上的操作,直到BFS到不了终点为止。
代码:
View Code
1 #include<iostream> 2 using namespace std; 3 #define INF 100000000 4 int cup[205][205]; 5 int a[205]; 6 int fa[205]; 7 int main(){ 8 int n,m; 9 while(cin>>m>>n){ 10 memset(cup,0,sizeof(cup)); 11 long long sum=0; 12 int end=n; 13 for(int i=1;i<=m;i++){ 14 int temp1,temp2,temp3; 15 cin>>temp1>>temp2>>temp3; 16 //cup[temp1][temp2]=(temp3>cup[temp1][temp2])?temp3:cup[temp1][temp2]; 17 cup[temp1][temp2]+=temp3; 18 } 19 while(1){ 20 memset(a,-1,sizeof(a)); 21 memset(fa,-1,sizeof(fa)); 22 a[1]=INF; 23 int p[205]; 24 int first1=0; 25 int last=0; 26 p[last++]=1; 27 while(last!=first1){ 28 int q=p[first1++]; 29 if(q==end) 30 break; 31 // cout<<"q "<<q<<" "<<first1<<" "<<last<<endl; 32 for(int j=1;j<=n;j++){ 33 if(a[j]==-1&&cup[q][j]>0){ 34 a[j]=(a[q]<cup[q][j])?a[q]:cup[q][j]; 35 fa[j]=q; 36 p[last++]=j; 37 } 38 } 39 } 40 if(a[end]==-1) 41 break; 42 for(int k=end;k!=1;k=fa[k]){ 43 cup[fa[k]][k]-=a[end]; 44 cup[k][fa[k]]+=a[end]; 45 } 46 sum+=a[end]; 47 // cout<<a[end]<<endl; 48 } 49 cout<<sum<<endl; 50 } 51 return 0; 52 }
Dinic:
算法:
构图和以上的FF类似;
先用BFS得出层次图,用dis[]存储各节点的层次;
再用DFS找出层次图中层次为递增的点的序列;用a[]来记录和标记找出的路径中的最小流量;
更新残余网络图,具体与上种情况类似;
重做以上操作,直到层次图中到达不了终点为止。
代码:
View Code
1 #include<iostream> 2 using namespace std; 3 #define INF 100000000 4 int cup[100][100]; 5 int a[100]; 6 int dis[100]; 7 int fa[100]; 8 int n,m,end; 9 int DFS(int re){ 10 if(re==end) 11 return 0; 12 int i; 13 for(i=1;i<=n;i++){ 14 if(cup[re][i]>0&&a[i]==-1&&(dis[i]==(dis[re]+1))){ 15 a[i]=a[re]<cup[re][i]?a[re]:cup[re][i]; 16 fa[i]=re; 17 int temp=DFS(i); 18 if(temp==0) 19 break; 20 else{ 21 a[i]=-1; 22 continue; 23 } 24 } 25 } 26 if(i>n) 27 return 1; 28 return 0; 29 } 30 int main(){ 31 while(cin>>n>>m){ 32 memset(cup,0,sizeof(cup)); 33 int sum=0; 34 end=n; 35 for(int i=1;i<=m;i++){ 36 int temp1,temp2,temp3; 37 cin>>temp1>>temp2>>temp3; 38 cup[temp1][temp2]+=temp3; 39 } 40 while(1){ 41 memset(dis,-1,sizeof(dis)); 42 int p[100]; 43 int first1=0; 44 int last=0; 45 p[last++]=1; 46 dis[1]=1; 47 while(first1!=last){ 48 int q=p[first1++]; 49 for(int j=1;j<=n;j++){ 50 if(cup[q][j]>0&&dis[j]==-1){ 51 dis[j]=dis[q]+1; 52 p[last++]=j; 53 } 54 } 55 } 56 if(dis[end]==-1) 57 break; 58 memset(a,-1,sizeof(a)); 59 memset(fa,-1,sizeof(fa)); 60 a[1]=INF; 61 DFS(1); 62 for(int g=end;g!=1;g=fa[g]){ 63 cup[fa[g]][g]-=a[end]; 64 cup[g][fa[g]]+=a[end]; 65 } 66 sum+=a[end]; 67 } 68 cout<<sum<<endl; 69 } 70 return 0; 71 }

浙公网安备 33010602011771号