网络流入门----pku1273

 

#include < iostream >
#include
< queue >
using   namespace  std;
#define  MAX_N 205
#define  MAX_M 205
const   int  INF = 0x7fffffff ;
int  map[MAX_M][MAX_M],pre[MAX_M];
// int flow[MAX_M];
int  s,e,c,n,m;
int  bfs();
int  EDmonds_Karp();
int  main()
{
    
while (scanf( " %d%d " , & n, & m) != EOF){
        memset(map,
0 , sizeof (map));
        
while (n -- ){
            scanf(
" %d %d %d " , & s, & e, & c);
            map[s][e]
+= c;
        }
        s
= 1 ;e = m;
        printf(
" %d\n " ,EDmonds_Karp());
    }
    
return   0 ;
}
int  EDmonds_Karp()
{
    
int  max_flow = 0 ,cur,min;
    
while ((min = bfs()) !=- 1 ){     // 找增广路径,找到,则构造残余网络
        max_flow += min;
        
for (cur = e;cur != s;cur = pre[cur]){
            map[pre[cur]][cur]
-= min;     // 更新正向边的实际流量
            map[cur][pre[cur]] += min;     // 添加反向边
        }
    }
    
return  max_flow;
}
int  bfs()
{
    
int  i,tmp,min;
    queue
< int > q;                 // 保存优先扩展出来的顶点的队列
//     while(!q.empty())    q.pop();
    memset(pre, - 1 , sizeof (pre));         // pre数组存储当前已访问过结点的增广路径
    pre[s] = 0 ;
//     flow[s]=INF;   // flow数组存储一次BFS遍历之后流的可改进量
    q.push(s);
    
while ( ! q.empty()){
        tmp
= q.front();q.pop();
        
if (tmp == e)    {             // 增广路径找到
//             break;
            min = INF;
            
for (i = e;i != s;i = pre[i])
                min
= map[pre[i]][i] < min ? map[pre[i]][i]:min;
            
return  min;
        }
        
for (i = 1 ;i <= e;i ++ ){
            
if (i != s && pre[i] ==- 1 && map[tmp][i]){       // 检测到一个顶点未访问且允许流量增加
//                 flow[i]=flow[tmp]<map[tmp][i]?flow[tmp]:map[tmp][i];
                q.push(i);
                pre[i]
= tmp;
            }
        }
    }
    
return   - 1 ;
//     if(pre[e]==-1)    return -1;
//     return flow[e];
}
题目地址: http://acm.pku.edu.cn/JudgeOnline/problem?id=1273

你可能感兴趣的:(pku)