Mai intai trebuie sa te autentifici.
Cod sursa(job #3377501)
| Utilizator | Data | 23 noiembrie 2026 14:50:33 | |
|---|---|---|---|
| Problema | Flux maxim | Scor | 100 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 1.75 kb |
// Edmonds Karp
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 1e3;
vector<int> G[NMAX + 1];
int flux[NMAX + 1][NMAX + 1];
int capacitate[NMAX + 1][NMAX + 1];
int n,m;
int p[NMAX + 1], vis[NMAX + 1];
int ek(int sursa, int destinatie) {
for (int i = 1; i <= n; i++) {
p[i] = vis[i] = 0;
}
queue<int> q;
q.push(sursa);
while (!q.empty()) {
int node = q.front();
q.pop();
for (auto vec : G[node]) {
if (!vis[vec] && capacitate[node][vec] - flux[node][vec] > 0) {
q.push(vec);
vis[vec] = 1;
p[vec] = node;
}
}
}
if (vis[destinatie] == 0) {
return 0;
}
vector<int> drum;
int x = destinatie;
while (x != sursa) {
drum.push_back(x);
x = p[x];
}
drum.push_back(sursa);
reverse(drum.begin(), drum.end());
int flow = 1e9;
for (int i = 0; i < drum.size() - 1; i++) {
int x = drum[i];
int y = drum[i+1];
int val = capacitate[x][y] - flux[x][y];
if (val < flow) {
flow = val;
}
}
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() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b, c;
fin >> a >> b >> c;
G[a].push_back(b);
capacitate[a][b] = c;
G[b].push_back(a);
}
int sum = 0;
while (true) {
int flux = ek(1, n);
if (flux == 0) {
break;
}
sum += flux;
}
fout << sum;
return 0;
}