最大流——最大传输量

日后有时间在详细解说 先将代码附上
C++实现代码如下:
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
typedef struct edge {
	int to, cap, rev;
}Edge;
#define MAX_V  5
#define INF 99999999
vector<Edge> G[MAX_V];
bool used[MAX_V];
void add_edge(int from, int to, int cap) {
	G[from].push_back(Edge{ to, cap, (int)G[to].size() });
	G[to].push_back(Edge{ from,0,(int)G[from].size() - 1 });
}

int min(int a, int b) {
	return a < b ? a : b;
}

int dfs(int v, int t, int f) {
	if (v == t)
		return f;
	used[v] = true;
	for (int i = 0; i < G[v].size(); ++i) {
		Edge &e = G[v][i];
		if (!used[e.to] && e.cap > 0) {
			int d = dfs(e.to, t, min(f, e.cap));
			if (d > 0) {
				e.cap -= d;
				G[e.to][e.rev].cap += d;
				cout << "e.rev = " << e.rev << endl;
				cout << d << endl;
				return d;
			}
		}
	}
	return 0;
}
int max_flow(int s, int t) {
	int flow = 0;
	for (;;) {
		memset(used, 0, sizeof(used));
		int f = dfs(s, t, INF);
		if (f == 0) {
			return flow;
		}
		flow += f;
		cout << f << " " << flow << endl;
		//flow += f;
	}
	return -1;
}
int main()
{		
	cout << "请输入源和目的地:";
	int r, s;
	cin >> r >> s;

	cout << "接下来请输入每条边的信息(from,to,cap)当from=-1的时候终止输入:" << endl;
	int from, to, cap;
	cin >> from >> to >> cap;

	while (from != -1){
		add_edge(from, to, cap);
		cin >> from >> to >> cap;
	}
	cout << "源到目的地的最大流为 " <<max_flow(r, s) << endl;
	

    return 0;
}
测试 数据:
1 5
1 2 10
1 3 2
2 3 6
2 4 6
3 5 5
4 3 3
4 5 8
-1 0 0
答案是11

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值