Pagini recente » Cod sursa (job #1267604) | Borderou de evaluare (job #1549324) | Cod sursa (job #3337018) | Cod sursa (job #3337028) | Cod sursa (job #3336368)
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <fstream>
using namespace std;
const int MAX = 1005;
const int INF = 1e9;
int capacitate[MAX + 1][MAX + 1], flux[MAX + 1][MAX + 1];
vector<int> G[MAX + 1];
int viz[MAX + 1], tata[MAX + 1];
int n, m, maxflow;
int bfs() {
for (int i = 1; i <= n; i++) {
viz[i] = tata[i] = 0;
}
queue<int> q;
q.push(1);
while (!q.empty()) {
int nod = q.front();
q.pop();
if (viz[nod] == 0) {
viz[nod] = 1;
for (const auto &vecin: G[nod]) {
if (viz[vecin] == 0 && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
q.push(vecin);
tata[vecin] = nod;
}
}
}
}
if (viz[n] == 0) {
return 0;
}
stack<int> st;
int nod = n;
while (nod != 0) {
st.push(nod);
nod = tata[nod];
}
vector<int> drum;
int flow = INF;
while (!st.empty()) {
drum.push_back(st.top());
st.pop();
}
for (int i = 0; i < drum.size() - 1; i++) {
int x = drum[i];
int y = drum[i + 1];
if (flow > capacitate[x][y] - flux[x][y]) {
flow = capacitate[x][y] - flux[x][y];
}
}
for (int i = 0; i < drum.size() - 1; i++) {
int x = drum[i];
int y = drum[i + 1];
flux[x][y] += flow;
flux[y][x] -= flow;
}
return flow;
}
int main() {
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, c;
fin >> x >> y >> c;
capacitate[x][y] = c;
//mergem pe graful rezidual
G[x].push_back(y);
G[y].push_back(x);
}
while (true) {
int flow = bfs();
if (flow == 0) {
break;
}
maxflow += flow;
}
fout << maxflow;
return 0;
}