#73-【Dinic模板】Flow Problem

版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82191397

Description

网络流是ACMers的一个众所周知的难题。 

给定一个图,你的任务是找出加权有向图的最大流量。

Input

第一行输入包含一个整数T,表示测试用例数。

对于每个测试用例,第一行包含两个整数N和M,表示图中顶点和边的数量。 (2 <= N <= 20,0 <= M <= 1000)

下一行M行,每行包含三个整数X,Y和C,从X到Y有一个边,其容量为C.(1 <= X,Y <= N,1 <= C <= 1000)

Output

对于每个测试用例,您应该输出从源1到接收器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 <cstring>
#include <queue>

#define SIZE 210
#define INF 2e+09

using namespace std;

struct edge
{
	int to, cap, reverse;
};

vector<edge> graph[SIZE];
int depth[SIZE], cur[SIZE], sink;

bool bfs(void) // bfs分层
{
	queue<int> q;
	int u, v, i;
	
	memset(depth, -1, sizeof (depth));
	depth[1] = 0;
	q.push(1);
	while (q.size())
	{
		u = q.front();
		q.pop();
		if (u == sink)
		{
			return true;
		}
		for (i = 0; i < graph[u].size(); ++i)
		{
			v = graph[u][i].to;
			if ((depth[v] == -1) && (graph[u][i].cap > 0))
			{
				depth[v] = depth[u] + 1;
				q.push(v);
			}
		}
	}
	
	return false;
}

int dfs(int u, int flow) // dfs增广
{
	int i, v, ret = 0, delta;
	
	if ((!flow) || (u == sink))
	{
		return flow;
	}
	for (i = 0; i < graph[u].size(); ++i)
	{
		cur[u] = i;
		edge &temp = graph[u][i];
		v = temp.to;
		if ((temp.cap > 0) && (depth[v] == depth[u] + 1))
		{
			delta = dfs(v, min(flow - ret, temp.cap));
			if (delta > 0)
			{
				ret += delta;
				temp.cap -= delta;
				graph[v][temp.reverse].cap += delta;
				if (ret == flow)
				{
					return ret;
				}
			}
		}
	}
	
	return ret;
}

int main(int argc, char** argv)
{
	int i, t, n, m, u, v, cap, ret, delta, count = 0;
	
	scanf("%d", &t);
	while (t--)
	{
		scanf("%d%d", &n, &m);
		sink = n;
		for (i = 1; i <= n; ++i) // 初始化
		{
			graph[i].clear();
		}
		while (m--)
		{
			scanf("%d%d%d", &u, &v, &cap);
			graph[u].push_back({v, cap, graph[v].size()});
			graph[v].push_back({u, 0, graph[u].size() - 1});
		}
		ret = 0;
		while (bfs()) // 日常Dinic
		{
			memset(cur, 0, sizeof (cur));
			delta = dfs(1, INF);
			if (!delta)
			{
				break;
			}
			ret += delta;
		}
		printf("Case %d: %d\n", ++count, ret);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/82191397
今日推荐