HDU 3549 —— Flow Problem

原题:http://acm.hdu.edu.cn/showproblem.php?pid=3549


题意:求 1 到 n 的最大流,模板题;


#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<vector>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 1100;
int cas, n, m, T = 0;

struct Edge
{
	int from, to, cap, flow;
}edge[maxn*2];

vector<int>G[maxn];
int edgenum;
void add(int u, int v, int c)
{
	edge[edgenum].from = u;
	edge[edgenum].to = v;
	edge[edgenum].flow = 0;
	edge[edgenum].cap = c;
	edgenum++;
	
	edge[edgenum].from = v;
	edge[edgenum].to = u;
	edge[edgenum].cap = 0;
	edge[edgenum].flow = 0;
	edgenum++;
	
	G[u].push_back(edgenum-2);
	G[v].push_back(edgenum-1);
}


int d[maxn];
bool vis[maxn];
void BFS(int s, int t)
{
	memset(vis, false, sizeof vis);
	queue<int>Q;
	Q.push(t);
	vis[t] = true;
	d[t] = 0;
	while(!Q.empty())
	{
		int now = Q.front();	
		Q.pop();
		for(int i = 0;i<(int)G[now].size();i++)
		{
			int v = edge[G[now][i]].to;
			if(!vis[v])
			{
				d[v] = d[now] + 1;
				Q.push(v);
				vis[v] = true;
			}
		}
	}
}

int front[maxn];
int Augment(int s, int t)
{
	int begin = t;
	int minflow = inf;
	while(begin != s)
	{
		Edge& e = edge[front[begin]];
		minflow = min(minflow, e.cap - e.flow);
		begin = e.from;
	}
	begin = t;
	while(begin != s)
	{
		edge[front[begin]].flow += minflow;
		edge[front[begin]^1].flow -= minflow;
		begin = edge[front[begin]].from;
	}
	return minflow;
}

int gap[maxn], cur[maxn];
int Maxflow(int s, int t)
{
	int flow = 0;
	BFS(s, t);
	memset(gap, 0, sizeof gap);
	memset(cur, 0, sizeof cur);
	for(int i = 1;i<=n;i++)
		gap[d[i]]++;
	int top = s;
	while(d[s] < n)
	{
		if(top == t)
		{
			flow += Augment(s, t);
			top = s;
		}
		bool flag = false;
		for(int i = cur[top];i<(int)G[top].size();i++)
		{
			Edge& e = edge[G[top][i]];
			if(e.cap > e.flow && d[e.from] == d[e.to] + 1)
			{
				flag = true;
				front[e.to] = G[top][i];
				cur[top] = i;
				top = e.to;
				break;
			}
		}
		if(!flag)
		{
			int m = n-1;
			for(int i = 0;i<(int)G[top].size();i++)
			{
				Edge& e = edge[G[top][i]];
				if(e.cap > e.flow)
					m = min(m, d[e.to]);
			}
			if(--gap[d[top]] == 0)	break;
			gap[d[top] = m+1]++;
			cur[top] = 0;
			if(top != s)
			{
				top = edge[front[top]].from;
			}
		}
	}
	return flow;
}

void init()
{
	for(int i = 1;i<=n;i++)	G[i].clear();
	edgenum = 0;
	memset(d, 0, sizeof d);
}

int main()
{
	scanf("%d", &cas);
	while(cas--)
	{		
		scanf("%d%d", &n, &m);
		init();
		while(m--)
		{
			int u, v, c;
			scanf("%d%d%d", &u, &v, &c);
			add(u, v, c);
		}
		int ans = Maxflow(1, n);
		printf("Case %d: %d\n", ++T, ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值