Pagini recente » Cod sursa (job #953658) | Cod sursa (job #1392074) | Cod sursa (job #1406846) | Cod sursa (job #2064381) | Cod sursa (job #3189343)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#include <cstring>
#define NMAX 1000
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int V, E;
int capacity[NMAX][NMAX];
int parent[NMAX];
vector<int> adj[NMAX];
int getAugmentingPathBFS() {
memset(parent, -1, sizeof(parent));
queue<pair<int, int>> q;
int currNode = 0, currMin = INT_MAX;
// holds {node, current min}
q.emplace(currNode, currMin);
while (!q.empty()) {
currNode = q.front().first;
currMin = q.front().second;
q.pop();
for (auto &neighbor: adj[currNode]) {
if (parent[neighbor] == -1 && capacity[currNode][neighbor] != 0) {
currMin = min(currMin, capacity[currNode][neighbor]);
parent[neighbor] = currNode;
if (neighbor == V - 1) {
return currMin;
}
q.emplace(neighbor, currMin);
}
}
}
return 0;
}
int getMaxFlow() {
int totalFlow = 0, newPathFlow;
newPathFlow = getAugmentingPathBFS();
while (newPathFlow) {
totalFlow += newPathFlow;
int currNode = V - 1;
while (currNode != 0) {
int ancestor = parent[currNode];
capacity[ancestor][currNode] -= newPathFlow;
capacity[currNode][ancestor] += newPathFlow;
currNode = ancestor;
}
newPathFlow = getAugmentingPathBFS();
}
return totalFlow;
}
int main()
{
fin >> V >> E;
memset(capacity, 0, sizeof(capacity));
int x, y, w;
for (int i = 0; i < E; ++i) {
fin >> x >> y >> w;
--x, --y;
adj[x].push_back(y);
adj[y].push_back(x);
capacity[x][y] = w;
}
fout << getMaxFlow();
return 0;
}