求點1到N 的最大流
代碼:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
typedef pair<int,int> pii;
const int maxn=1006<<1;
int n,m;
struct node {
int v,nex,cap,flow;
};
struct Dinic{
int head[maxn];
int st,la;//源點和匯點
int vis[maxn],tot;
node edge[maxn];
void init(){
tot=0;
memset (head,-1,sizeof (head));
}
void addedge(int u,int v,int c){
edge[tot]=node{v,head[u],c,0};
head[u]=tot++;
edge[tot]=node{u,head[v],0,0};
head[v]=tot++;
}
int bfs(){
memset (vis,0,sizeof (vis));
queue<int>q;
q.push(st);
vis[st]=1;
while (!q.empty()){
int u=q.front();q.pop();
for (int i=head[u];i!=-1;i=edge[i].nex){
int v=edge[i].v,cap=edge[i].cap,flow=edge[i].flow;
if(vis[v]==0&&cap>flow){
vis[v]=vis[u]+1;
if (v==la){
return 1;
}
q.push(v);
}
}
}
return 0;
}
int dfs(int u,int flow){
if (u==la||flow==0){
return flow;
}
int ans=0,tmp;
for (int i=head[u];i!=-1;i=edge[i].nex){
int v=edge[i].v,cap=edge[i].cap,f=edge[i].flow;
if ((vis[v]==vis[u]+1)&&(tmp=dfs(v,min(cap-f,flow)))>0){
edge[i].flow+=tmp;
edge[i^1].flow-=tmp;
ans+=tmp;
flow-=tmp;
if (flow==0)break;
}
}
return ans;
}
int max_flow(int s,int t){
this->st=s;
this->la=t;
int ans=0;
while (bfs()){
while (1){
int tmp=dfs(st,inf);
if (tmp==0)break;
ans+=tmp;
}
}
return ans;
}
}dinic;
int main ()
{
int T;
scanf ("%d",&T);
int cnt=1;
while(T--){
dinic.init();
scanf ("%d%d",&n,&m);
int u,v,c;
for (int i=0;i<m;i++){
scanf ("%d%d%d",&u,&v,&c);
dinic.addedge(u,v,c);
}
printf ("Case %d: %d\n",cnt++,dinic.max_flow(1,n));
}
return 0;
}