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