Pagini recente » Cod sursa (job #12647) | Profil ana_madalina_18 | Cod sursa (job #483141) | Cod sursa (job #1851213) | Cod sursa (job #2440392)
#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];
bool viz[N];
int tata[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;
// 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 nod, int val) {
if (nod == t)
return val;
int ans(0);
for (int i : g[nod]) {
if (tata[i] == nod && viz[i] && cap[nod][i] - f[nod][i] > 0) {
int x = aug(i, min(val, cap[nod][i] - f[nod][i]));
f[nod][i] += x;
f[i][nod] -= x;
ans += x;
val -= x;
}
}
return ans;
}
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()) {
ans += aug(s, 2e9);
}
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;
}