增广路网络流算法的实现

利用队列,每次都找出是否存在从开始点到终止点存在不为零的流的数量,如果存在的话,那么就将最终的结果增加相应的数量,同时要记录相应的路径,对于路径上的那些边的流量也要进行对应地增加,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;

class Edge{
public:
	int from, to, cap, flow;
};

class Graph{
public:
	int n, m;
	vector<Edge> edge;
	vector<int> graph[1005];
	int parent[1005];
	int remain[1005];

	void Init(){
		cin >> n >> m;
		for (int i = 0; i < m; i++){
			Edge temp;
			cin >> temp.from >> temp.to >> temp.cap;
			temp.flow = 0;
			Edge temp2;
			temp2.from = temp.to;
			temp2.to = temp.from;
			temp2.cap = 0;
			temp2.flow = 0;
			edge.push_back(temp);
			edge.push_back(temp2);
			graph[temp.from].push_back(edge.size() - 2);
			graph[temp.to].push_back(edge.size() - 1);
		}
		memset(parent, -1, sizeof(parent));
	}

	void Deal(int s,int t){
		Init();
		int total_flow = 0;
		while (true){
			memset(remain,0,sizeof(remain));
			queue<int> q;
			q.push(s);
			remain[s] = 1 << 30;
			while (!q.empty()){
				int id = q.front();
				q.pop();
				for (int i = 0; i < graph[id].size(); i++){
					int ide = graph[id][i];
					int from = edge[ide].from;
					int to = edge[ide].to;
					if (!remain[to]&&edge[ide].cap > edge[ide].flow){
						parent[to] = ide;
						remain[to] = min(remain[from], edge[ide].cap - edge[ide].flow);
						q.push(to);
					}
				}
				if (remain[t]) break;
			}
			if (!remain[t]) break;
			for (int i = t; i != s;i=edge[parent[i]].from){
				edge[parent[i]].flow += remain[t];
				edge[parent[i] ^ 1].flow -= remain[t];
			}
			total_flow += remain[t];
		}
		cout << "The total flow is " << total_flow << endl;
	}
};

int main(){
	Graph G;
	G.Deal(1,4);
	system("pause");
	return 0;
}

/*
测试数据:
6 10
1 2 16
1 5 13
2 3 12
3 4 20
6 3 7
6 4 4
2 5 10
5 2 4
3 5 9
5 6 14

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值