Pagini recente » Cod sursa (job #2366265) | Cod sursa (job #2383444) | Cod sursa (job #532140) | Cod sursa (job #2785082) | Cod sursa (job #2852006)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
typedef pair <int, int> PII;
const int NMAX = 1003, INF = 1e9;
int n, m, maxf;
bool sel[NMAX];
vector < int > G[NMAX];
int flux[NMAX][NMAX];
int cap[NMAX][NMAX], T[NMAX];
int mymin(int a, int b)
{
return (a < b ? a : b);
}
void Reset()
{
maxf = 0;
for(int i = 1; i <= n; ++i)
sel[i] = T[i] = 0;
}
bool BFS(int S, int D)
{
Reset();
sel[S] = true;
queue < int > q;
q.push(S);
while(!q.empty()) {
int node = q.front();
q.pop();
for(auto it: G[node]) {
if(!sel[it] && cap[node][it] > flux[node][it])
q.push(it), sel[it] = 1, T[it] = node;
}
}
return sel[D];
}
int maxflow(int S, int D)
{
int ans = 0;
int fmax = 0;
while(BFS(S, D)) {
for(auto it: G[D]) {
if(sel[it]) {
fmax = cap[it][D] - flux[it][D];
int node = it;
while(node != S) {
fmax = mymin(fmax, cap[T[node]][node] - flux[T[node]][node]);
node = T[node];
}
node = it;
flux[it][D] += fmax;
while(node != S) {
flux[T[node]][node] += fmax;
node = T[node];
}
ans += fmax;
}
}
}
return ans;
}
int main()
{
fin >> n >> m;
int x, y, c;
for (int i = 1; i <= m; ++i) {
fin >> x >> y >> c;
G[x].push_back(y);
G[y].push_back(x);
cap[x][y] = c;
}
fout << maxflow(1, n) << '\n';
return 0;
}