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.
题解:
最大流模板题,dinic
AC代码:
#pragma GCC optimize(2)
#include<bits/stdc++.h>
#include<ext/rope>
using namespace std;
using namespace __gnu_cxx;
#define LL long long
const int MAXN = 2020;
const int MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
int n,m,s,t,tot,head[MAXN],w[MAXN],nxt[MAXN],to[MAXN],h[MAXN];
inline void ade(int u,int v,int ww){
to[++tot]=v; w[tot]=ww; nxt[tot]=head[u]; head[u]=tot;
}
inline void add(int u,int v,int w){ ade(u,v,w); ade(v,u,0); }
inline int bfs(){
queue<int> que; que.push(s); memset(h,0,sizeof(h)); h[s]=1;
while(!que.empty()){
int u=que.front(); que.pop();
for(int i=head[u];i;i=nxt[i]){
if(w[i] && !h[to[i]]){
h[to[i]]=h[u]+1; que.push(to[i]);
}
}
}
return h[t];
}
inline int dfs(int x,int f){
if(x==t) return f; int fl=0;
for(int i=head[x];i&&f;i=nxt[i]){
if(w[i] && h[to[i]]==h[x]+1){
int mi=dfs(to[i],min(f,w[i]));
w[i]-=mi; w[i^1]+=mi; fl+=mi; f-=mi;
}
}
if(!fl) h[x]=-1;
return fl;
}
inline int dinic(){
int res=0;
while(bfs()) res+=dfs(s,INF);
return res;
}
signed main(){
#ifndef ONLINE_JUDGE
freopen("C:\\Users\\Administrator\\Desktop\\in.txt","r",stdin);
#endif // ONLINE_JUDGE
int T,cas=0; scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m); s=1,t=n,tot=1;
memset(head,0,sizeof(head));
for(int i=1,u,v,w;i<=m;i++) scanf("%d%d%d",&u,&v,&w),add(u,v,w);
printf("Case %d: %d\n",++cas,dinic());
}
return 0;
}