Pagini recente » Cod sursa (job #2878237) | Cod sursa (job #1897222) | Cod sursa (job #2156597) | Cod sursa (job #413722) | Cod sursa (job #2744306)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 1000;
const int MMAX = 5000;
const int INF = 110000000;
struct muchie {
int from, to;
int cf;
muchie(int _from = 0, int _to = 0, int _cf = 0) : from(_from), to(_to), cf(_cf) {}
};
int n, m;
int sursa, dest;
vector<int> v[NMAX + 5];
muchie muchii[2 * MMAX + 5];
int dad_mch[NMAX + 5];
void add_muchie(int from, int to, int cap, int idx) {
muchii[idx] = muchie(from, to, cap);
v[from].push_back(idx);
}
void read() {
scanf("%d %d", &n, &m);
sursa = 1;
dest = n;
for(int i = 0; i < m; i++) {
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
add_muchie(x, y, z, 2 * i);
add_muchie(y, x, 0, 2 * i + 1);
}
}
void bfs(int start) {
queue<int> q;
q.push(start);
for(int i = 1; i <= n; i++)
dad_mch[i] = -1;
dad_mch[sursa] = -2;
while(!q.empty()) {
int nod = q.front();
q.pop();
if(nod == dest)
continue;
for(int idx_mch: v[nod]) {
int vec = muchii[idx_mch].to;
if(dad_mch[vec] != -1 || muchii[idx_mch].cf == 0)
continue;
dad_mch[vec] = idx_mch;
q.push(vec);
}
}
}
void add_flow(int nod, int &new_flow) {
if(dad_mch[nod] == -2)
return;
new_flow = min(new_flow, muchii[ dad_mch[nod] ].cf);
add_flow(muchii[ dad_mch[nod] ].from, new_flow);
muchii[ dad_mch[nod] ].cf -= new_flow;
muchii[ dad_mch[nod] ^ 1 ].cf += new_flow;
}
void solve() {
int max_flow = 0;
dad_mch[dest] = 1;
while(dad_mch[dest] != -1) {
bfs(sursa);
for(int idx_mch: v[dest]) {
int nod = muchii[idx_mch].to;
if(dad_mch[nod] != -1 && muchii[idx_mch ^ 1].cf > 0) {
dad_mch[dest] = idx_mch ^ 1;
int new_flow = INF;
add_flow(dest, new_flow);
max_flow += new_flow;
}
}
}
printf("%d", max_flow);
}
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
read();
solve();
return 0;
}