this is a very good question for beginning to learn network flow , very easy way to use ff algorithm .
to solve the max flow problem ,we need to calculate the rest flow network,so we update the reverse edges when applying dfs to find the answer.
Need more work in graphic theory……
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
const int M=25;
int INF=0x3f3f3f3f3f;
struct edge
{
int to,cap;
unsigned int rev;
};
vector<edge> G[M];
//add a edge with volume of cap to the map from s to t
void add_edge(int from,int to,int cap)
{
G[from].push_back((edge)
{
to,cap,G[to].size()
});
G[to].push_back((edge)
{
from,0,G[from].size()-1
});
}
//find extend path by dfs
bool used[M];
int dfs(int v,int t,int f)
{
if(v==t) return f;
used[v] = true;
for(unsigned int i=0; i<G[v].size(); i++)
{
edge &e=G[v][i];
if(!used[e.to] && e.cap>0)
{
int d=dfs(e.to,t,min(f,e.cap));
if(d>0)
{
e.cap-=d;
G[e.to][e.rev].cap+=d;
return d;
}
}
}
return 0;
}
int max_flow(int s,int t)
{
int flow=0;
while(1)
{
memset(used,0,sizeof(used));
int f=dfs(s,t,INF);
if(f==0) return flow;
flow+=f;
}
}
int main()
{
int T;
scanf("%d",&T);
for(int t = 1; t<=T; t++)
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<=n;i++)
{
G[i].clear();
}
for(int i=0; i<m; i++)
{
int s,t,c;
scanf("%d%d%d",&s,&t,&c);
add_edge(s,t,c);
}
printf("Case %d: %d\n",t,max_flow(1,n));
}
return 0;
}