Pagini recente » Cod sursa (job #623699) | Cod sursa (job #2042936) | Borderou de evaluare (job #736699) | Cod sursa (job #2787931) | Cod sursa (job #2440390)
#include <fstream>
#include <cassert>
#include <vector>
#include <cstring>
using namespace std;
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
const int N = 1009;
vector < int > g[N];
int cap[N][N];
namespace FLUX {
int s, t, n;
int dq[N];
int tata[N];
bool viz[N];
int f[N][N];
int w[N];
bool bfs() {
memset(viz, 0, sizeof viz);
int st(0), dr(-1);
dq[++dr] = s;
viz[s] = 1;
while (st <= dr) {
int x = dq[st++];
if (x == t)
continue;
// cout << x << ' ' << g[x].size() << '\n';
for (int i : g[x]) {
// cout << i << ' ';
if (viz[i] == 0 && cap[x][i] > f[x][i]) {
tata[i] = x;
viz[i] = 1;
dq[++dr] = i;
w[i] = min(w[x], cap[x][i] - f[x][i]);
// cout << "da ";
}
// else {
// cout << "nu ";
// }
}
// cout << '\n';
}
// cout << "BFS : \n";
// for (int i = 1; i <= n; ++i) {
// if (i != t && i != s)
// cout << tata[i] << ' ';
// }
// cout << '\n';
return (viz[t] == 1);
}
long long aug(int hatz) {
int nod = hatz;
int cost(min(w[hatz], cap[hatz][t] - f[hatz][t]));
if (cost == 0)
return 0;
// cout << "Aug : \n" << cost << '\n';
// cout << t << ' ';
tata[t] = nod;
nod = t;
while (tata[nod] != -1) {
f[nod][tata[nod]] -= cost;
f[tata[nod]][nod] += cost;
// cout << nod << ' ';
nod = tata[nod];
}
// cout << '\n';
return cost;
}
long long flux(const int &_n, const int &_s, const int &_t) {
memset(f, 0, sizeof f);
s = _s;
n = _n;
t = _t;
tata[s] = -1;
w[s] = 1e9 + 7;
assert(max(s, t) <= n && min(s, t) >= 1);
long long ans(0);
while (bfs()) {
for (int i : g[t])
if (viz[i] == 1 && cap[i][n] > f[i][n])
ans += aug(i);
}
return ans;
}
}
int main() {
int n, m, x, y, z;
cin >> n >> m;
while (m--) {
cin >> x >> y >> z;
cap[x][y] += z;
g[x].push_back(y);
g[y].push_back(x);
}
cout << FLUX::flux(n, 1, n);
return 0;
}