Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 45239 | Accepted: 17002 |
Description
Farmer John knows not only how many gallons of water each ditch can transport per minute but also the exact layout of the ditches, which feed out of the pond and into each other and stream in a potentially complex network.
Given all this information, determine the maximum rate at which water can be transported out of the pond and into the stream. For any given ditch, water flows in only one direction, but there might be a way that water can flow in a circle.
Input
Output
Sample Input
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
Sample Output
50
Source
思路:网络流入门,建图无难度。我用的是最短增广路径算法。复杂度是O(n*m*m)
#include<iostream> #include<cstring> using namespace std; const int mm=210; const int oo=1e9; class node { public:int c,f; node(){c=f=0;} }e[mm][mm]; int pre[mm],le[mm][mm],q[mm]; int m,n,s,t,a,b,c; void path_add()///找增广路径 { memset(le,0,sizeof(le)); memset(pre,-1,sizeof(pre)); pre[1]=-2;int qs=0,qt=1;q[qs]=1; int z; while(qs!=qt&&pre[t]==-1) { z=q[qs++];qs%=mm; for(int i=1;i<=n;i++) { if(pre[i]==-1) { if(e[z][i].c-e[z][i].f>0)///le[][]为残留网络 le[z][i]=e[z][i].c-e[z][i].f,pre[i]=z,q[qt++]=i,qt%=mm; else if(e[i][z].f>0) le[z][i]=e[i][z].f,pre[i]=z,q[qt++]=i,qt%=mm; } } } } int flow_go() { if(pre[t]==-1)return 0; int ret=oo,u,v; for(u=pre[t],v=t;u!=-2;v=u,u=pre[u])///找出最小流 { if(ret>le[u][v])ret=le[u][v]; } if(ret>0) { u=pre[t];v=t; while(u!=-2)///更改网络 { if(e[u][v].c-e[u][v].f>0) e[u][v].f+=ret; else if(e[v][u].f>0) e[u][v].f+=ret; v=u;u=pre[u]; } return ret; } else return 0; } int flow_max() { int ret=0,z; while(1) { path_add(); z=flow_go(); ret+=z; if(z==0)return ret; } } int main() { while(cin>>m>>n) { memset(e,0,sizeof(e)); for(int i=0;i<m;i++) { cin>>a>>b>>c; e[a][b].c+=c; }s=1;t=n; cout<<flow_max()<<"\n"; } }