Pagini recente » Cod sursa (job #288881) | Cod sursa (job #1984686) | Cod sursa (job #2712505) | Cod sursa (job #1318903) | Cod sursa (job #2957273)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int dim = 1005;
int n,m, sursa, destinatie;
vector<pair<int,pair<int,int>>> graf_rezidual[dim];
pair<int, int*> tata[dim];
int viz[dim];
vector<pair<int,int*>> in_destinatie;
int BFS() {
queue<int> q;
for (int i=1; i<=n; i++) {
viz[i] = 0;
}
tata[sursa] = {0, 0};
viz[sursa] = 1;
q.push(sursa);
while (!q.empty()) {
int x = q.front();
q.pop();
if (x == destinatie) continue;
for (auto &y:graf_rezidual[x]) {
if (y.second.first > 0 && !viz[y.first]) {
viz[y.first] = 1;
tata[y.first] = {x, &y.second.first};
q.push(y.first);
}
}
}
return viz[destinatie];
}
int main() {
in >> n >> m;
int x, y, c;
sursa = 1;
destinatie = n;
while (m--) {
in >> x >> y >> c;
graf_rezidual[x].push_back({y, {c, 1}});
graf_rezidual[y].push_back({x, {0, 0}});
if (y == destinatie) {
in_destinatie.push_back({x, &graf_rezidual[x][graf_rezidual[x].size() - 1].first});
}
}
int maxflow = 0;
while (BFS()) {
pair<int,int*> nod = tata[destinatie];
int mini = 1e9;
while (nod.first != 0) {
mini = min(mini, *nod.second);
nod = tata[nod.first];
}
maxflow += mini;
nod = tata[destinatie];
while (nod.first != 0) {
*nod.second -= mini;
nod = tata[nod.first];
}
}
out << maxflow;
return 0;
}