Pagini recente » Cod sursa (job #3176355) | Cod sursa (job #2807754) | Cod sursa (job #37189) | Monitorul de evaluare | Cod sursa (job #3336702)
#include<iostream>
#include<vector>
#include <queue>
#include<fstream>
#define pii pair<int, int>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 1000, inf = 1e9;
vector<int> g[NMAX];
int cap[NMAX][NMAX], n;
int bfs (int s, int t, int parent[]) {
for (int i = 1; i <= n; i++) {
parent[i] = -1;
}
parent[s] = -2;
queue<pii> q;
q.push({s, inf});
while(!q.empty()) {
int nod = q.front().first;
int flow = q.front().second;
q.pop();
for (auto neigh: g[nod]) {
if (parent[neigh] == -1 && cap[nod][neigh]) {
parent[neigh] = nod;
int next_flow = min(flow, cap[nod][neigh]);
if (neigh == t) {
return next_flow;
}
q.push({neigh, next_flow});
}
}
}
return 0;
}
int maxflow(int source, int destination) {
int flow = 0, curr_flow, parent[NMAX];
while ((curr_flow = bfs(source, destination, parent))) {
int nod = destination;
flow += curr_flow;
while (nod != source) {
int prev = parent[nod];
cap[prev][nod] -= curr_flow;
cap[nod][prev] += curr_flow;
nod = prev;
}
}
return flow;
}
int main () {
int m, x, y, z;
fin >> n >> m;
for (int i = 0; i < m; i++) {
fin >> x >> y >> z;
g[x].push_back(y);
g[y].push_back(x);
cap[x][y] = cap[y][x] = z;
}
fout << maxflow(1, n);
}