Pagini recente » Cod sursa (job #2088066) | Cod sursa (job #2209834) | Cod sursa (job #3326916) | Cod sursa (job #2165513) | Cod sursa (job #3328570)
//
// Created by h4rapa1b on 12/9/25.
//
#include <algorithm>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int NMAX = 1e3;
int capacitate[NMAX+1][NMAX+1];
int flux[NMAX+1][NMAX+1];
vector<int> grafic[NMAX+1];
int vis[NMAX+1], parent[NMAX+1];
int bfs(int s, int d) {
// mark toate nodurile ca nevizitate
for (int i = 1; i <= NMAX; ++i) {
vis[i] = 0;
}
queue<int> q;
q.push(s);
vis[s] = 1;
while (!q.empty()) {
int nod = q.front();
q.pop();
for (auto vecin : grafic[nod]) {
if (!vis[vecin] && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
vis[vecin] = 1;
q.push(vecin);
parent[vecin] = nod;
}
}
}
if (!vis[d]) {
return 0; // nu exista drum de augmentare
}
// determinam drum de la s la d si bagam flux pe acel drum
vector<int> path;
int x = d;
while (x != 0) {
path.push_back(x);
x = parent[x];
}
reverse(path.begin(), path.end());
int flow = 1e9;
for (int i = 0; i < path.size() - 1; ++i) {
int u = path[i];
int v = path[i + 1];
flow = min(flow, capacitate[u][v] - flux[u][v]);
}
for (int i = 0; i < path.size() - 1; ++i) {
int u = path[i];
int v = path[i + 1];
flux[u][v] += flow;
flux[v][u] -= flow;
}
return flow;
}
int main() {
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n, m;
fin >> n >> m;
// citim muchiile si costurile
for (int i = 1; i <= m; ++i) {
int u, v, c;
fin >> u >> v >> c;
capacitate[u][v] = c;
grafic[u].push_back(v);
grafic[v].push_back(u); // muchie inversa pentru graf rezidual
}
int maxflow = 0;
while (true) {
int flow = bfs(1, n);
if (flow == 0) {
break; // nu mai exista drumuri de augmentare
}
maxflow += flow;
}
fout << maxflow << "\n";
fin.close();
fout.close();
return 0;
}