Problem is from:http://poj.org/problem?id=1459
Edmond Karp最大流
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 #define MAXN 110 8 int n,map[MAXN][MAXN],pre[MAXN]; 9 bool flag[MAXN]; 10 11 //BFS()寻找增广路 12 bool BFS(int start,int end){ 13 queue<int> que; 14 int k; 15 memset(pre,-1,sizeof(pre)); 16 memset(flag,true,sizeof(flag)); 17 que.push(start); 18 flag[start]=false; 19 while(!que.empty()){ 20 k=que.front(); 21 if(k==end) 22 return true; 23 que.pop(); 24 for(int i=0;i<n;i++){ 25 if(map[k][i] && flag[i]){ 26 flag[i]=false; 27 pre[i]=k; 28 que.push(i); 29 } 30 } 31 } 32 return false; 33 } 34 35 //MaxFlow()返回最大流 36 int MaxFlow(int start,int end){ 37 int ans=0,k,minf; 38 while(BFS(start,end)){ 39 minf=-1; 40 k=end; 41 while(pre[k]!=-1){ 42 if(minf<0) 43 minf=map[pre[k]][k]; 44 else 45 minf=min(minf,map[pre[k]][k]); 46 k=pre[k]; 47 } 48 ans+=minf; 49 k=end; 50 while(pre[k]!=-1){ 51 map[pre[k]][k]-=minf; 52 map[k][pre[k]]-=minf; 53 k=pre[k]; 54 } 55 } 56 return ans; 57 } 58 59 int main() 60 { 61 int np,nc,m,u,v,z,start,end; 62 while(scanf("%d%d%d%d",&n,&np,&nc,&m)!=EOF){ 63 memset(map,0,sizeof(map)); 64 start=n;end=n+1; 65 for(int i=0;i<m;i++){ 66 scanf(" (%d,%d)%d",&u,&v,&z); 67 map[u][v]=z; 68 } 69 for(int i=0;i<np;i++){ 70 scanf(" (%d)%d",&v,&z); 71 map[start][v]=z; 72 } 73 for(int i=0;i<nc;i++){ 74 scanf(" (%d)%d",&u,&z); 75 map[u][end]=z; 76 } 77 n+=2; 78 printf("%d\n",MaxFlow(start,end)); 79 } 80 return 0; 81 }
直接套模版...