HDU-3549 Flow Problem 最基础的网络流 ʕ •ᴥ•ʔ

  • Post author:
  • Post category:其他


Flow Problem


Time Limit: 5000/5000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)

Total Submission(s): 1252    Accepted Submission(s): 606

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.

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 <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <map>
#include<queue> 
#define ll long long
#define pi acos(-1.0)
#define N 0x3f3f3f3f
using namespace std;
int n,m;
int s,e;
int x[1010][1010];
int depth[1010];
// bfs 分层图 
int bfs()
{
	queue<int>q;
	memset(depth,-1,sizeof(depth));
	depth[s]=0;
	q.push(s);
	while(!q.empty())
	{
		int temp=q.front();
		q.pop();
		for(int i=1;i<=n;i++)
		{
			if(x[temp][i]&&depth[i]<0)
			{
				depth[i]=depth[temp]+1;
				q.push(i);
			}
		}
	}
	if(depth[e]>0)
	return 1;
	return 0;
}
// 搜索增广路径 
int dfs(int here,int h)
{
	// 若找到了汇点返回此增长路径 
	if(here==e)
	return h;
	int now;
	for(int i=1;i<=n;i++)
	{
		// 1 判断这条路是否连通
		// 2 判断 here 点和 i 点是不是上下层的关系
		// 3 找到流入 和 管道允许的最小值 并往下 搜索  
		if(x[here][i]&&depth[here]==depth[i]-1&&(now=dfs(i,min(h,x[here][i]))))
		{
			x[here][i]-=now; // 把流走的流量减掉  
			x[i][here]+=now; // 可以 "反悔"  
			return now;
		}
	}
	return 0;
}
int main()
{
	int t;
	cin>>t;
	int Case=1;
	while(t--)
	{
		cin>>n>>m;
		memset(x,0,sizeof(x));
		for(int i=1;i<=m;i++)
		{
			int a,b,c;
			cin>>a>>b>>c;
			x[a][b]+=c;// 有可能有重边 
		}
		s=1,e=n;
		int ans=0;
		while(bfs()) //先分层 再搜索 
		{
			ans+=dfs(s,N);
		}
		printf("Case %d: %d\n",Case++,ans);
	}
	return 0;
} 



版权声明:本文为henucm原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。