Pagini recente » Cod sursa (job #720582) | Cod sursa (job #1747742) | Cod sursa (job #1902942) | Cod sursa (job #234312) | Cod sursa (job #2956970)
#include <bits/stdc++.h>
using namespace std;
// Find the maximum flow of a flow network using Edmonds-Karp algorithm and optimize it using BFS
// Time complexity: O(V*E^2)
const int NMAX = 100; // maximum number of nodes
const int INF = 0x3f3f3f3f; // infinite value
int n, m; // number of nodes and edges
int source, sink; // source and sink
int capacity[NMAX][NMAX]; // capacity matrix
int flow[NMAX][NMAX]; // flow matrix
int parent[NMAX]; // parent vector
// read the input
void readInput() {
ifstream fin("maxflow.in");
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, c;
fin >> x >> y >> c;
capacity[x][y] = c;
}
source = 1;
sink = n;
fin.close();
}
// find the maximum flow of the network using Edmonds-Karp algorithm
int maxFlow() {
int maxFlow = 0;
while (true) {
// find an augmenting path using BFS
queue<int> q;
q.push(source);
for (int i = 1; i <= n; i++)
parent[i] = 0;
parent[source] = -1;
while (!q.empty() && parent[sink] == 0) {
int node = q.front();
q.pop();
for (int i = 1; i <= n; i++)
if (parent[i] == 0 && capacity[node][i] > flow[node][i]) {
q.push(i);
parent[i] = node;
}
}
// if there is no augmenting path, the algorithm stops
if (parent[sink] == 0)
break;
// compute the bottleneck capacity
int bottleNeck = INF;
for (int i = sink; i != source; i = parent[i])
bottleNeck = min(bottleNeck, capacity[parent[i]][i] - flow[parent[i]][i]);
// update the flow
for (int i = sink; i != source; i = parent[i]) {
flow[parent[i]][i] += bottleNeck;
flow[i][parent[i]] -= bottleNeck;
}
maxFlow += bottleNeck;
}
return maxFlow;
}
// print the maximum flow
void printMaxFlow() {
ofstream fout("maxflow.out");
fout << maxFlow() << endl;
fout.close();
}
int main() {
readInput();
printMaxFlow();
return 0;
}