HDU 3549 Flow Problem【E-K+BFS 最大流】

Problem Description
Network flow is a well-known difficult problem for ACMers. Given a graph, your task is to find out the maximum flow for the weighted directed graph.
Input
The first line of input contains an integer T, denoting the number of test cases.
For each test case, the first line contains two integers N and M, denoting the number of vertexes and edges in the graph. (2 <= N <= 15, 0 <= M <= 1000)
Next M lines, each line contains three integers X, Y and C, there is an edge from X to Y and the capacity of it is C. (1 <= X, Y <= N, 1 <= C <= 1000)
Output
For each test cases, you should output the maximum flow from source 1 to sink N.
Sample Input
2
3 2
1 2 1
2 3 1
3 3
1 2 1
2 3 1
1 3 1
Sample Output
Case 1: 1
Case 2: 2
分析: 使用BFS 可以应对数据不***钻的题目,DFS很容易慢。
             使用Edmonds-Karp算法。
CODE:
View Code
#include<stdio.h>
#include<string.h>
#define min(a,b)((a)<(b))?(a):(b)
#define clr(a) memset(a,0,sizeof(a))
#define maxn 16
#define inf 999999
int q[1000];
int flow[maxn][maxn];
int c[maxn][maxn];
int a[maxn];
int p[maxn];
int front,rear,s,t,n,m,i,maxflow,u,v,w;
int main()
{
int ca,k=1;
scanf("%d",&ca);
while(ca--)
{
clr(flow);clr(p);clr(c);
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
c[u][v]+=w;
}
s=1;t=n;
maxflow=0;
for(;;)
{
clr(a);
a[s]=inf;
front=rear=0;
q[rear++]=s;
while(front<rear) //BFS 找增广路
{
u=q[front];
front++;
for(v=1;v<=n;v++)
if(!a[v]&&c[u][v]>flow[u][v]) //找到新节点 v
{
p[v]=u; //记录 v 的父亲,并加入队列
q[rear++]=v;
a[v]=min(a[u],c[u][v]-flow[u][v]); //s-v 路径上的最小残量
}
}
if(a[t]==0)break; //找不到,则当前流是最大流
for(u=t;u!=s;u=p[u]) //从汇点往回走
{
flow[p[u]][u]+=a[t]; //更新正向流量
flow[u][p[u]]-=a[t]; //更新反向流量
}
maxflow+=a[t]; //更新从 s 流出的总流量
}
printf("Case %d: %d\n",k++,maxflow);
}
return 0;
}




posted @ 2012-03-15 00:52  'wind  阅读(222)  评论(0编辑  收藏  举报