Nu aveti permisiuni pentru a descarca fisierul grader_test5.ok
Cod sursa(job #2247146)
Utilizator | Data | 27 septembrie 2018 22:16:03 | |
---|---|---|---|
Problema | Flux maxim | Scor | 100 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.96 kb |
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
struct maxFlow {
vector<int>G[MAXN];
int from[MAXN];
struct Edge {
int x, y, cap, flow, inv;
int other(int nod) {
return x ^ y ^ nod;
}
int ramas() {
return cap - flow;
}
};
vector<Edge> E;
void addEdge(int x, int y, int c) {
E.push_back({x, y, c, 0, E.size() + 1});
G[x].push_back(E.size() - 1);
E.push_back({y, x, 0, 0, E.size() - 1});
G[y].push_back(E.size() - 1);
}
bool bfs(int s, int d) {
queue<int>q;
q.push(s);
memset(from, -1, sizeof(from));
from[s] = 0;
while (!q.empty() && from[d] == -1) {
int aux = q.front();
q.pop();
for (auto it:G[aux]) {
int x = E[it].other(aux);
if (from[x] == -1 && E[it].ramas() > 0) {
from[x] = it;
q.push(x);
}
}
}
return (from[d] != -1);
}
int baga(int s, int d) {
int ans = 0;
while (bfs(s, d)) {
for (auto it:G[d]) {
int minim = (1LL << 31) - 1;
if (minim == E[E[it].inv].ramas() > 0 || from[E[it].other(d)] == -1)
continue;
int nod = d;
int muc = E[it].inv;
while (nod != s) {
minim = min(minim, E[muc].ramas());
nod = E[muc].other(nod);
muc = from[nod];
}
nod = d;
muc = E[it].inv;
while (nod != s) {
E[muc].flow += minim;
E[E[muc].inv].flow -= minim;
nod = E[muc].other(nod);
muc = from[nod];
}
ans += minim;
}
}
return ans;
}
};
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
int n, m;
scanf("%d%d", &n, &m);
maxFlow s;
for (int i = 1; i <= m; ++i) {
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
s.addEdge(x, y, c);
}
printf("%d\n", s.baga(1, n));
return 0;
}