Pagini recente » Cod sursa (job #2582959) | Cod sursa (job #2535479) | Cod sursa (job #1286081) | Clasament simulare_oji_2024_clasele_11_12_13_februarie | Cod sursa (job #2961694)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 1005;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n, m;
vector<vector<int>> adj;
int flux[NMAX][NMAX];
bool visited[NMAX];
int pred[NMAX];
int total;
bool bfs() {
queue<int> q;
// Initialize all nodes as not visited and no predecessor
for (int i = 1; i <= n; i++) {
pred[i] = 0;
visited[i] = false;
}
// Mark the source as visited and add it to the queue
visited[1] = true;
q.push(1);
while (!q.empty()) {
int node = q.front();
q.pop();
for (auto& neighbor : adj[node]) {
// If neighbor is not visited and there is residual capacity
// in the edge (node, neighbor), visit it
if (!visited[neighbor] && flux[node][neighbor] > 0) {
pred[neighbor] = node;
q.push(neighbor);
visited[neighbor] = true;
// If we reach the sink, return true
if (neighbor == n)
return true;
}
}
}
// If we can't reach the sink, return false
return false;
}
int main() {
fin >> n >> m;
adj.resize(n + 1);
// Read the edges and add them to the adjacency list
for (int i = 1; i <= m; i++) {
int x, y, z;
fin >> x >> y >> z;
adj[x].push_back(y);
adj[y].push_back(x);
flux[x][y] = z;
}
// While there is a path from source to sink
while (bfs()) {
// For each neighbor of the sink
for (auto& neighbor : adj[n]) {
// If the neighbor is not visited, skip it
if (!visited[neighbor])
continue;
// Find the minimum flow through the path from source to sink
int min_flow = INT32_MAX;
int node = n;
while (node != 1) {
min_flow = min(min_flow, flux[pred[node]][node]);
node = pred[node];
}
// Decrease the residual capacity of the edges in the path
// and increase the residual capacity of the reverse edges
node = n;
while (node != 1) {
flux[pred[node]][node] -= min_flow;
flux[node][pred[node]] += min_flow;
node = pred[node];
}
// Add the minimum flow to the total flow
total += min_flow;
}
}
// Output the total flow
fout << total;
return 0;
}