Pagini recente » Cod sursa (job #1116621) | Cod sursa (job #815640) | Cod sursa (job #3162068) | Cod sursa (job #3291214) | Cod sursa (job #2962648)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int dim = 1005;
int n,m, sursa, destinatie;
vector<pair<int,pair<long long 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 (int i=0; i<graf_rezidual[x].size(); i++) {
auto y = graf_rezidual[x][i];
if (y.second.first > 0 && !viz[y.first]) {
viz[y.first] = 1;
tata[y.first] = {x, i};
q.push(y.first);
}
}
}
return viz[destinatie];
}
void PrintMinCut() {
BFS();
for (int i=1; i<=n; i++) {
if (viz[i]) {
cout << i << " ";
}
}
cout << "\n\n";
for (int i=1; i<=n; i++) {
if (!viz[i]) {
cout << i << " ";
}
}
}
int main() {
in >> n >> m;
int x, y;
long long int c;
sursa = 1;
destinatie = n;
while (m--) {
in >> x >> y >> c;
graf_rezidual[x].push_back({y, {c, 0}});
graf_rezidual[y].push_back({x, {0, 0}});
graf_rezidual[x][graf_rezidual[x].size() - 1].second.second = graf_rezidual[y].size()-1;
graf_rezidual[y][graf_rezidual[y].size() - 1].second.second = graf_rezidual[x].size()-1;
if (y == destinatie) {
in_destinatie.push_back({x, graf_rezidual[x].size() - 1});
}
}
long long int maxflow = 0;
while (BFS()) {
for (auto y:in_destinatie) {
tata[destinatie] = y;
pair<int, int> nod = tata[destinatie];
int catre = destinatie;
long long int mini = LONG_LONG_MAX;
while (nod.first != 0) {
mini = min(mini, graf_rezidual[nod.first][nod.second].second.first);
nod = tata[nod.first];
}
maxflow += mini;
nod = tata[destinatie];
while (nod.first != 0) {
int poz = graf_rezidual[nod.first][nod.second].second.second;
graf_rezidual[nod.first][nod.second].second.first -= mini;
graf_rezidual[catre][poz].second.first += mini;
catre = nod.first;
nod = tata[nod.first];
}
}
}
out << maxflow;
// PrintMinCut();
return 0;
}