用c++或者c语言写一个含有Fold-fulkerson算法的可行代码,输入为节点数以及多条有向带权边,然后再用dinic算法优化它
时间: 2024-03-27 19:35:25 浏览: 62
一个c++程序设计,包括算法与数据结构
以下是使用C++实现的Fold-Fulkerson算法和Dinic算法:
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Edge {
int from, to, cap, flow;
};
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
vector<Edge> edges;
vector<int> G[MAXN];
int d[MAXN], cur[MAXN];
int n, m, s, t;
void addEdge(int from, int to, int cap) {
edges.push_back((Edge){from, to, cap, 0});
edges.push_back((Edge){to, from, 0, 0});
int m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool bfs() {
memset(d, -1, sizeof(d));
queue<int> q;
q.push(s);
d[s] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (d[e.to] == -1 && e.cap > e.flow) {
d[e.to] = d[u] + 1;
q.push(e.to);
}
}
}
return d[t] != -1;
}
int dfs(int u, int a) {
if (u == t || a == 0) return a;
int flow = 0, f;
for (int &i = cur[u]; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (d[u] + 1 == d[e.to] && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0) {
e.flow += f;
edges[G[u][i] ^ 1].flow -= f;
flow += f;
a -= f;
if (a == 0) break;
}
}
return flow;
}
int dinic() {
int flow = 0;
while (bfs()) {
memset(cur, 0, sizeof(cur));
flow += dfs(s, INF);
}
return flow;
}
int maxflow() {
int flow = 0;
while (bfs()) {
memset(cur, 0, sizeof(cur));
flow += dfs(s, INF);
}
return flow;
}
int dfs_fold_fulkerson(int u, int t, int f) {
if (u == t) return f;
int flow = 0;
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (e.cap > e.flow && d[e.to] == d[u] + 1) {
int g = dfs_fold_fulkerson(e.to, t, min(f, e.cap - e.flow));
if (g == 0) d[e.to] = -1;
e.flow += g;
edges[G[u][i] ^ 1].flow -= g;
flow += g;
f -= g;
if (f == 0) break;
}
}
return flow;
}
int fold_fulkerson() {
int flow = 0;
while (true) {
memset(d, -1, sizeof(d));
queue<int> q;
q.push(s);
d[s] = 0;
if (!bfs()) break;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (d[e.to] == -1 && e.cap > e.flow) {
d[e.to] = d[u] + 1;
q.push(e.to);
}
}
}
flow += dfs_fold_fulkerson(s, t, INF);
}
return flow;
}
int main() {
cin >> n >> m >> s >> t;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
addEdge(u, v, w);
}
cout << "Max flow: " << maxflow() << endl;
cout << "Fold-Fulkerson max flow: " << fold_fulkerson() << endl;
return 0;
}
```
该代码首先读入节点数、边数、源点和汇点,然后使用 `addEdge` 函数将每条带权边添加到图中。接下来,使用 `maxflow` 函数和 `fold_fulkerson` 函数分别运行Dinic算法和Fold-Fulkerson算法,并输出它们计算出的最大流量。
阅读全文