Pagini recente » Cod sursa (job #2836061) | Cod sursa (job #1952168) | Cod sursa (job #842300) | Cod sursa (job #2942486) | Cod sursa (job #2956086)
#include <fstream>
#include <queue>
using namespace std;
const int maxN = 1024;
const int infi = 1 << 30;
struct Muchie {
int src, dest;
int flx, cap;
Muchie (int _src = 0, int _dest = 0, int _flx = 0, int _cap = 0):
src(_src), dest(_dest), flx(_flx), cap(_cap) { }
} father[maxN];
vector<Muchie> G[maxN];
int cost[maxN];
void clear(int N) {
for (int i = 1; i <= N; i ++) {
cost[i] = infi;
father[i] = Muchie();
}
}
bool bfs(int N) {
clear(N);
queue<int> q;
cost[1] = 0; q.push(1);
while(!q.empty()) {
int top = q.front(); q.pop();
for (auto it: G[top]) {
if (cost[top] + 1 < cost[it.dest] && it.flx < it.cap) {
cost[it.dest] = cost[top] + 1;
father[it.dest] = it;
q.push(it.dest);
}
}
}
return cost[N] != infi;
}
int main() {
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int N, M;
in >> N >> M;
for (int i = 1; i <= M; i ++) {
int src, dest, cap;
in >> src >> dest >> cap;
G[src].push_back(Muchie(src, dest, 0, cap));
G[dest].push_back(Muchie(dest, src, 0, 0));
}
while(bfs(N)) {
vector<Muchie> drum;
int x = N;
while(father[x].src) {
drum.push_back(father[x]);
x = father[x].src;
}
int max_flow = infi;
for (auto it: drum)
max_flow = min(max_flow, it.cap - it.flx);
for (auto edge: drum) {
bool found = false;
for (int i = 0; i < (int)G[edge.src].size() && !found; i ++) {
if (G[edge.src][i].dest == edge.dest) {
G[edge.src][i].flx += max_flow;
found = true;
}
}
found = false;
for (int i = 0; i < (int)G[edge.dest].size() && !found; i ++) {
if (G[edge.dest][i].dest == edge.src) {
G[edge.dest][i].flx -= max_flow;
found = true;
}
}
}
}
int flux = 0;
for (auto it: G[1])
flux += it.flx;
out << flux << '\n';
return 0;
}