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.
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
Hint
Source
HyperHexagon's Summer Gift (Original tasks)
终于弄懂了ek算法,一起来感受最大流的美妙吧。
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int maxData = 0x7fffffff;
queue<int>q;
int n,m;
int G[20][20];//存路
int pre[20];记录前驱结点
int flow[20];//记录流量,开始我想用单一变量记录,后来发现不行
void intit()
{
for(int i=0;i<=n;i++)
{
pre[i]=-1;
}
}
int Bfs(int s,int t)//寻找路径
{
while(!q.empty())
{
q.pop();
}
intit();
//pre[s]=0;
q.push(s);
flow[s]=maxData;
while(!q.empty())
{
int x=q.front();
q.pop();
if(x==t)
break;
for(int i=1;i<=n;i++)
{
if(i!=s&&G[x][i]>0&&pre[i]==-1)
{
q.push(i);
flow[i]=min(flow[x],G[x][i]);
pre[i]=x;
}
}
}
if(pre[t]==-1)
return -1;
else
return flow[t];
}
int maxflow(int s,int t)
{
int sum=0;
int sumflow=0;
while((sum=Bfs(s,t))!=-1)
{
int i=t;
while(pre[i]!=-1)
{
G[pre[i]][i]-=sum;
G[i][pre[i]]+=sum;//反向边,开始以为无关紧要,后来知道必要;
i=pre[i];
}
sumflow+=sum;
}
return sumflow;
}
int main()
{
int t;
scanf("%d",&t);
int fg=0;
while(t--)
{
fg++;
//memset(flow,0,sizeof(flow));//这个有不有应该是无所谓的
memset(G,0,sizeof(G));
scanf("%d%d",&n,&m);
int a,b,x;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&x);
G[a][b]+=x;//用+=防止同一路径多次出现;
}
printf("Case %d: %d\n",fg,maxflow(1,n));
}
}