网络最大流

#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <cstring>

using namespace std;

int n, m, src, dst, depth[10001], ec;
struct EDGE
{
	int to, weight;
	EDGE() { }
	EDGE(int t, int w) { to = t, weight = w; }
} edge[100001];
list<int> g[10001]; typedef list<int>::iterator li;

void insert_edge(int s, int d, int w = 1)
{
	edge[ec] = EDGE(d, w);
	g[s].push_back(ec++);
	edge[ec] = EDGE(s, 0);
	g[d].push_back(ec++);
}

bool bfs()
{
	memset(depth, 0, sizeof(depth));
	queue<int> q; EDGE e;
	depth[src] = 1;
	q.push(src);
	do
	{
		int p = q.front();
		q.pop();
		for(li i = g[p].begin(); i != g[p].end(); i++)
		{
			e = edge[*i];
			if(e.weight > 0 && !depth[e.to])
			{
				depth[e.to] = depth[p] + 1;
				if(e.to == dst) return true;
				q.push(e.to);
			}
		}
	} while(!q.empty());
	return false;
}

int dfs(int p, int cur)
{
	if(p == dst) return cur;
	EDGE e; int ret = 0;
	for(li i = g[p].begin(); i != g[p].end(); i++)
	{
		e = edge[*i];
		if(depth[e.to] == depth[p] + 1 && e.weight)
		{
			int c = dfs(e.to, min(cur - ret, e.weight));
			if(c > 0)
			{
				edge[*i].weight -= c;
				edge[*i ^ 1].weight += c;
				ret += c;
				if(ret >= cur) break;
			}
		}
	}
	if(!ret) depth[p] = 0;
	return ret;
}

int main()
{
	int s, d, w;
	scanf("%d%d%d%d", &n, &m, &src, &dst);
	for(int i = 1; i <= m; i++)
	{
		scanf("%d%d%d", &s, &d, &w);
		insert_edge(s, d, w);
	}
	int s = 0;
	while(bfs())
		s += dfs(src, 0x3f3f3f3f);
	printf("%d\n", s);
}
posted @ 2018-02-21 22:23  Js2xxx  阅读(147)  评论(0编辑  收藏  举报