Pagini recente » Cod sursa (job #2851693) | Cod sursa (job #2248581) | Cod sursa (job #2252683) | Cod sursa (job #3243672) | Cod sursa (job #2414823)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("maxflow.in"); ofstream fout ("maxflow.out");
const int nmax = 1e3;
const int inf = 1 << 30;
int n;
struct edge {
int x, f, cap, indop;
edge () {}
edge (int _x, int _f, int _cap, int _indop) {
x = _x, f = _f, cap = _cap, indop = _indop;
}
};
vector<edge> e;
vector<int> g[nmax + 1];
void trage_muchie (int x, int y, int c) {
g[x].push_back(e.size());
e.push_back(edge(y, 0, c, e.size() + 1));
g[y].push_back(e.size());
e.push_back(edge(x, 0, 0, e.size() - 1));
}
int h[nmax + 1];
int pos[nmax + 1];
queue<int> q;
bool bfs () {
for (int i = 1; i <= n; ++ i)
h[i] = 0;
q.push(1);
h[1] = 1;
while (!q.empty()) {
int x = q.front();
q.pop();
for (auto i : g[x]) {
if (e[i].f < e[i].cap && h[e[i].x] == 0) {
h[e[i].x] = h[x] + 1;
q.push(e[i].x);
}
}
}
return h[n] > 0;
}
int dfs (int nod, int _f) {
if (nod == n)
return _f;
if (_f == 0)
return 0;
while (pos[nod] < g[nod].size() &&
(e[g[nod][pos[nod]]].f == e[g[nod][pos[nod]]].cap || h[e[g[nod][pos[nod]]].x] != h[nod] + 1)) {
++ pos[nod];
}
if (pos[nod] == g[nod].size())
return 0;
int ind = g[nod][pos[nod]];
int fl = dfs(e[ind].x, min(_f, e[ind].cap - e[ind].f));
e[ind].f += fl;
e[e[ind].indop].f -= fl;
return fl;
}
int dinitz () {
int ans = 0;
while (bfs()) {
for (int i = 1; i <= n; ++ i)
pos[i] = 0;
int x = dfs(1, inf);
while (x > 0) {
ans += x;
x = dfs(1, inf);
}
}
return ans;
}
int main () {
int m;
fin >> n >> m;
for (int i = 1; i <= m; ++ i) {
int x, y, z;
fin >> x >> y >> z;
trage_muchie(x, y, z);
}
fout << dinitz() << "\n";
fin.close();
fout.close();
return 0;
}