Pagini recente » Cod sursa (job #2668812) | Cod sursa (job #255417) | Cod sursa (job #564768) | Cod sursa (job #3136860) | Cod sursa (job #2959088)
#include <fstream>
#include <vector>
#include <iostream>
#include <string.h>
#include <string>
#include <sstream>
#include <climits>
#include <queue>
using namespace std;
int n, m, maxFlow;
vector<vector<int>> adjList;
vector<vector<int>> capacityMap;
vector<vector<int>> flowMap;
vector<int> parentMap;
ifstream myIn("maxflow.in");
ofstream myOut("maxflow.out");
void ReadInputs() {
myIn >> n >> m;
adjList.resize(n);
capacityMap.resize(n, vector<int>(n));
flowMap.resize(n, vector<int>(n));
parentMap.resize(n, -1);
parentMap[0] = INT_MAX;
for (int i = 0; i < m; i++) {
int x, y, f;
myIn >> x >> y >> f; x--; y--;
adjList[x].push_back(y);
capacityMap[x][y] = f;
capacityMap[y][x] = f;
}
}
bool BFS() {
fill(parentMap.begin(), parentMap.end(), -1);
queue<int> q;
q.push(0);
while (q.empty() == false) {
int s = q.size();
for (int i = 0; i < s; i++) {
int currentNode = q.front();
q.pop();
if (currentNode == (n - 1)) {
return true;
}
for (int j = 0; j < adjList[currentNode].size(); j++) {
int nextNode = adjList[currentNode][j];
int flow = flowMap[currentNode][nextNode];
int capacity = capacityMap[currentNode][nextNode];
if ((parentMap[nextNode] == -1) && (capacity != flow)) {
q.push(nextNode);
parentMap[nextNode] = currentNode;
}
}
}
}
return false;
}
void EdmondsKarp() {
while (BFS() == true) {
int minFlow = INT_MAX;
int node = n - 1;
do {
int nextNode = parentMap[node];
minFlow = min(minFlow, capacityMap[node][nextNode] - flowMap[node][nextNode]);
node = nextNode;
} while (node != 0);
node = n - 1;
do {
int nextNode = parentMap[node];
flowMap[node][nextNode] += minFlow;
flowMap[nextNode][node] += minFlow;
node = nextNode;
} while (node != 0);
maxFlow += minFlow;
}
}
void Output() {
myOut << maxFlow;
myOut.close();
myIn.close();
}
int main() {
ReadInputs();
EdmondsKarp();
Output();
}