网络流的基础题,EK算法模板,留着...
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <climits>
#define MAX 20
#define INF 0x7FFFFFFF
# define eps 1e-5
//#pragma comment(linker, "/STACK:36777216") ///传说中的外挂
using namespace std;
int cap[MAX][MAX],flow[MAX],pre[MAX];
int n,m;
void init()
{
memset(cap,0,sizeof(cap));
memset(flow,0,sizeof(flow));
}
int bfs(int s,int e)
{
queue<int >q;
memset(pre,-1,sizeof(pre));
pre[s] = 0;
flow[s] = INF;
q.push(s);
while(! q.empty())
{
int t = q.front();
q.pop();
if(t == e)
break;
for(int i=1; i<=n; i++)
{
if(i != s && cap[t][i] > 0 && pre[i] == -1) // 相连且未被访问过
{
pre[i] = t;
flow[i] = min(cap[t][i],flow[t]); // 更新该点的改进流量
q.push(i);
}
}
}
if(pre[e] == -1)
return -1;
else
return flow[e];
}
int maxflow(int s,int e)
{
int aug = 0;
int sumflow = 0;
while((aug = bfs(s,e)) != -1) //每一次找出残余流量
{
int ind = e;//利用pre来找前驱结点
while(ind != s)
{
cap[pre[ind]][ind] -= aug;
cap[ind][pre[ind]] += aug;
ind = pre[ind];
}
sumflow += aug;
}
return sumflow;
}
int main()
{
int tt = 1;
int t,a,b,c;
cin >> t;
while(t --)
{
init();
scanf("%d%d",&n,&m);
for(int i=0; i<m; i++)
{
scanf("%d%d%d",&a,&b,&c);
if(a == b)
continue;
cap[a][b] += c;
}
printf("Case %d: ",tt++);
printf("%d\n",maxflow(1,n));
}
return 0;
}