求最大流模板:
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <queue>
#include <string.h>
#include <vector>
#include <iomanip>
#include <map>
#include <stack>
#include <functional>
#include <list>
using namespace std;
#define MAX_POINT 300 // 点的最多数目
#define INF 99999999
struct edge { // 定义边,to为边所到端点,cap是容量,rev为反向边
int to;
int cap;
int rev;
edge() {}
edge(int tto, int ccap, int rrev) {
to = tto;
cap = ccap;
rev = rrev;
}
};
bool vis[MAX_POINT]; // 用于寻找路径的时候记录点是否被访问过
int points; // 点数
vector<edge> G[MAX_POINT]; // 图
void addEdge(int from, int to, int cap) { // 往图中加入一条从from到to容量为cap的路径
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1)); // 加入反向边
}
int makeSuperStart(vector<int> start) { // 若有多个源点,创造一个超级源点
if (start.size() == 1) return start[0];
int s = points;
points++;
for (int i = 0; i < start.size(); i++) {
addEdge(s, start[i], INF);
addEdge(start[i], s, INF);
}
return s;
}
int makeSuperEnd(vector<int> end) { // 若有多个汇点,创造一个超级汇点
if (end.size() == 1) return end[0];
int e = points;
points++;
for (int i = 0; i < end.size(); i++) {
addEdge(end[i], e, INF);
addEdge(e, end[i], INF);
}
return e;
}
int dfs(int from, int to, int lastCap) { // 通过深搜找到一条路径
if (from == to) return lastCap;
vis[from] = true;
for (int i = 0; i < G[from].size(); i++) {
edge & e = G[from][i];
if (!vis[e.to] && e.cap > 0) {
int nextFlow = dfs(e.to, to, min(lastCap, e.cap));
if (nextFlow > 0) {
e.cap -= nextFlow;
G[e.to][e.rev].cap += nextFlow;
return nextFlow;
}
}
}
return 0;
}
int MaxFlow(vector<int> start, vector<int> end) { // 用于找到最大流
int maxFlow = 0;
int s = makeSuperStart(start);
int e = makeSuperEnd(end);
while (1) {
memset(vis, false, sizeof(vis));
int f = dfs(s, e, INF);
if (f == 0) return maxFlow;
maxFlow += f;
}
return maxFlow;
}
以下给出两个例子,分别是有向图和无向图:
有向:
http://blog.csdn.net/u012925008/article/details/44538963
无向: