最大流入门

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

#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h> 
using namespace std;
int a[20][20];
int pre[20];
int vis[20];
int n,m;
bool dfs(int s,int t){
	queue<int>q;
	memset(pre,-1,sizeof(pre));
	memset(vis,0,sizeof(vis));
	vis[s]=1;
	q.push(s);
	pre[s]=s;
	while(!q.empty()){
		int now=q.front();
		q.pop();
		if(now==t){
			return 1;
		}
		for(int i=1;i<=n;i++){
			if(a[now][i]>0 && vis[i]!=1){
				q.push(i);
				vis[i]=1;
				pre[i]=now;
			}
		}
	}
	return 0;
}
int ek(int s,int t){
	int mmax=0;
	while(dfs(s,t)){
		int d=999999;
		for(int i=t;i!=s;i=pre[i]){
			d=min(d,a[pre[i]][i]);
		}
		for(int i=t;i!=s;i=pre[i]){
			a[pre[i]][i]-=d;
			a[i][pre[i]]+=d; 
		}
		mmax+=d;
	}
	return mmax;
} 
int main(){
	int t;
	int w=1;
	scanf("%d",&t);
	while(t--){
		scanf("%d %d",&n,&m);
		memset(a,0,sizeof((a)));
		int e,ee,c;
		for(int i=0;i<m;i++){
			scanf("%d %d %d",&e,&ee,&c);
			a[e][ee]+=c;
		}
		printf("Case %d: %d\n",w++,ek(1,n));
	}
} 

猜你喜欢

转载自blog.csdn.net/doublekillyeye/article/details/80616566