HDU 3549 Flow Problem【Ford-Fulkerson+DFS 最大流】

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
分析:网络流入门,最大流 Ford-Fulkerson方法DFS实现。
code 1;
View Code
#include<stdio.h>
#include<string.h>
#define maxn 16
#define inf 999999
int s,t,i,n,m,u,v,w,flow,maxflow;
int vis[maxn];
int c[maxn][maxn];
int dfs(int u,int low)
{
int i,flow;
if(u==t)
return low;
if(vis[u])
return 0;
vis[u]=1;
for(i=1;i<=n;i++)
if(c[u][i]&&(flow=dfs(i,low<c[u][i]?low:c[u][i])))
{
c[u][i]-=flow;
c[i][u]+=flow;
return flow;
}
return 0;
}
int main()
{
int ca,k=1;
scanf("%d",&ca);
while(ca--)
{
scanf("%d%d",&n,&m);
memset(c,0,sizeof(c));
memset(vis,0,sizeof(vis));
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
c[u][v]+=w;
}
s=1;t=n;
maxflow=0;
while(flow=dfs(s,inf))
{
maxflow+=flow;
memset(vis,0,sizeof(vis));
}
printf("Case %d: %d\n",k++,maxflow);
}
return 0;
}
code2:  多路增广
View Code
#include<stdio.h>
#include<string.h>
#define maxn 16
#define inf 9999999
int c[maxn][maxn];
int s,t,i,k,u,v,w,n,m;
int flow,maxflow;
int vis[maxn];
int dfs(int u,int low)
{
int i,flow;
int sum=0;
if(u==t)
return low;
if(vis[u])
return 0;
vis[u]=1;
for(i=1;i<=n;i++)
if(c[u][i]&&(flow=dfs(i,low<c[u][i]?low:c[u][i])))
{
sum+=flow;
low-=flow;
c[u][i]-=flow;
c[i][u]+=flow;
if(!low)
break;
}
return sum;
}
int main()
{
int ca,k=1;
scanf("%d",&ca);
while(ca--)
{
memset(vis,0,sizeof(vis));
memset(c,0,sizeof(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;
while(flow=dfs(s,inf))
{
maxflow+=flow;
memset(vis,0,sizeof(vis));
}
printf("Case %d: %d\n",k++,maxflow);
}
return 0;
}

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