Flow Problem Time Limit: 5000/5000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others) 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. 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 Author HyperHexagon Source |
题目大意:
t组数据,n个点,m条边,求最大流。
记录属于自己的模板!
Dinic 358ms
Ford_Fulkerson 1808ms
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define INF 0x3f3f3f3f
int head[100000];
struct edge
{
int from,to,w,next;
}e[1000000];
int div[100000];
int n,m,cont,ss,tt;
void add(int from,int to,int w)
{
e[cont].to=to;
e[cont].w=w;
e[cont].next=head[from];
head[from]=cont++;
}
int makediv()
{
memset(div,0,sizeof(div));
queue<int >s;
s.push(ss);
div[ss]=1;
while(!s.empty())
{
int u=s.front();
if(u==tt)return 1;
s.pop();
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
int w=e[i].w;
if(w&&div[v]==0)
{
div[v]=div[u]+1;
s.push(v);
}
}
}
return 0;
}
int Dfs(int u,int maxflow,int tt)
{
if(u==tt)return maxflow;
int ret=0;
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
int w=e[i].w;
if(w&&div[v]==div[u]+1)
{
int f=Dfs(v,min(maxflow-ret,w),tt);
e[i].w-=f;
e[i^1].w+=f;
ret+=f;
if(ret==maxflow)return ret;
}
}
return ret;
}
void Dinic()
{
ss=1;tt=n;
int ans=0;
while(makediv()==1)
{
ans+=Dfs(ss,INF,tt);
}
printf("%d\n",ans);
}
int main()
{
int t;
int kase=0;
scanf("%d",&t);
while(t--)
{
cont=0;
memset(head,-1,sizeof(head));
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
add(x,y,w);
add(y,x,0);
}
printf("Case %d: ",++kase);
Dinic();
}
}