题目链接:Flow Problem
题目大意:
T 组数据,每组给定m条边,求从 1 到 n 的最大流。。。
代码如下:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
#define maxn 10010
#define INF 1e9
struct No{
int to;
int ne;
int w;
}e[maxn<<2];
int head[maxn],deth[maxn];
int T,n,m,x,y,val,cnt;
void init()
{
cnt = 0;
memset(head,-1,sizeof(head));
}
void add(int u,int v,int val)
{
e[cnt].to = v;
e[cnt].ne = head[u];
e[cnt].w = val;
head[u] = cnt ++;
}
int bfs()
{
memset(deth,0,sizeof(deth));//这里注意每一次分层都要进行初始化。。。
queue<int>q;
deth[1] = 1;
q.push(1);
while(!q.empty())
{
int k = q.front();
q.pop();
for(int i=head[k];~i;i=e[i].ne)
{
int kk = e[i].to;
if(e[i].w && deth[kk] == 0)
{
deth[kk] = deth[k] + 1;
q.push(kk);
}
}
}
if(deth[n] == 0)
return 0;
return 1;
}
int dfs(int u,int dist)
{
if(u == n)
return dist;
for(int i=head[u];~i;i=e[i].ne)
{
int kk = e[i].to;
if(e[i].w != 0 && deth[kk] == deth[u] + 1)
{
int di = dfs(kk,min(dist,e[i].w));//向下增光
if(di>0)//如果可以增广
{
e[i].w -= di; // 正向减边
e[i^1].w += di;//反向加边
return di;//传递
}
}
}
return 0;//没有增光路,返回 0
}
int dinic()
{
int ans = 0;
while(bfs())
{
while(int di = dfs(1,INF))
ans += di;
}
return ans;
}
int main()
{
scanf("%d",&T);
int tot = 0;
while(T--)
{
init();
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&val);
add(x,y,val);
add(y,x,0);
}
printf("Case %d: %d\n",++tot,dinic());
}
return 0;
}