Pagini recente » Cod sursa (job #3240557) | Cod sursa (job #2656034) | Cod sursa (job #1800169) | Cod sursa (job #690999) | Cod sursa (job #3271204)
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
bool bfs(std::vector<std::vector<int> > &graf, std::vector<std::vector<int> > &flux, std::vector<int> &tata,
const int n) {
std::vector viz(n, false);
std::queue<int> q;
q.push(0);
viz[0] = true;
while (!q.empty()) {
const int i = q.front();
q.pop();
for (const auto &j: graf[i]) {
if (viz[j] || !flux[j][i])
continue;
tata[j] = i;
if (j == n - 1)
return true;
q.push(j);
viz[j] = true;
}
}
return false;
}
int main() {
std::vector<std::vector<int> > graf;
std::vector<std::vector<int> > flux;
int n;
int m;
int i, j, w;
std::ifstream f("maxflow.in");
f >> n >> m;
graf.resize(n);
flux.resize(n, std::vector(n, 0));
while (m--) {
f >> i >> j >> w;
graf[i - 1].push_back(j - 1);
graf[j - 1].push_back(i - 1);
flux[j - 1][i - 1] = w;
}
f.close();
int fluxMaxim = 0;
std::vector tata(n, -1);
while (bfs(graf, flux, tata, n)) {
int capRezMin = INT_MAX;
for (int aux = n - 1; aux != 0; aux = tata[aux])
capRezMin = std::min(capRezMin, flux[aux][tata[aux]]);
fluxMaxim += capRezMin;
for (int aux = n - 1; aux != 0; aux = tata[aux]) {
flux[aux][tata[aux]] -= capRezMin;
flux[tata[aux]][aux] += capRezMin;
}
}
std::ofstream g("maxflow.out");
g << fluxMaxim;
g.close();
return 0;
}