任重而道远
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)
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
题目大意:
给你一个N个顶点M条边的有向图,要你求1号点到N号点的最大流.
AC代码:
include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=20;
const int maxm=2005;
const int Inf=100000000;
int n,m,t,st=1,en;
bool vis[maxm];
struct edge
{
int nxt,tov,cf;
}e[maxm];
int h[maxn],num=1,q[maxn],dis[maxm],hh[maxn];
void add(int nxt,int tov,int cf)
{
num++;
e[num].tov=tov;
e[num].cf=cf;
e[num].nxt=h[nxt];
h[nxt]=num;
num++;
e[num].tov=nxt;
e[num].cf=0;
e[num].nxt=h[tov];
h[tov]=num;
}
int dfs(int x,int delta)
{
if (x==en)
return delta;
int rt=0;
for (int i=hh[x];i;i=e[i].nxt)
if (e[i].cf&&(dis[x]+1==dis[e[i].tov]))
{
int dd=dfs(e[i].tov,min(e[i].cf,delta));
delta-=dd;
e[i].cf-=dd;
e[i^1].cf+=dd;
rt+=dd;
hh[x]=i;
}
return rt;
}
bool bfs()
{
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
vis[st]=1;
int head=0,tail=0;
tail++;
q[0]=st;
while (head<tail)
{
int u=q[head++];
for (int i=h[u];i;i=e[i].nxt)
{
int v=e[i].tov;
if (!vis[v]&&e[i].cf)
{
q[tail++]=v;
dis[v]=dis[u]+1;
vis[v]=1;
}
}
}
return vis[en];
}
void init()
{
memset(e,0,sizeof(e));
memset(h,0,sizeof(h));
memset(q,0,sizeof(q));
num=1;
}
int main()
{
scanf("%d",&t);
for (int k=1;k<=t;k++)
{
init ();
scanf("%d%d",&n,&m);
en=n;
for (int i=1;i<=m;i++)
{
int f,t,v;
scanf("%d%d%d",&f,&t,&v);
add(f,t,v);
}
int ans=0;
while (bfs()) {
for (int i=1;i<=n;i++) hh[i]=h[i];
ans+=dfs(st,Inf);
}
printf("Case %d: %d\n",k,ans);
}
return 0;
}
本文详细介绍了网络流中的最大流问题,并提供了一段AC代码。针对有向图,文章解释了如何寻找从源点1到汇点N的最大流量,并通过样例输入输出展示了解决方案。
1万+

被折叠的 条评论
为什么被折叠?



