Pagini recente » Cod sursa (job #2075411) | Cod sursa (job #2327784) | Cod sursa (job #2203434) | Cod sursa (job #2328616) | Cod sursa (job #2902772)
#include <bits/stdc++.h>
#define Nmax 1002
using namespace std;
ifstream fin("p2.in");
ofstream fout("p2.out");
int N, M;
vector<int> G[Nmax];
int height[Nmax], cap[Nmax][Nmax], flow[Nmax][Nmax], overflow[Nmax];
int findVertex() {
for (int i = 2; i < N; ++i)
if (overflow[i] > 0) return i;
return -1;
}
bool push(int u) {
for (auto v: G[u])
if (height[u] > height[v] && cap[u][v] - flow[u][v] > 0) {
int pushFlow = min(overflow[u], cap[u][v] - flow[u][v]);
//cout << u << " " << v << " " << " " << pushFlow << "\n";
overflow[u] -= pushFlow; /// fluxul se deplaseaza pe directia muchiei u -> v
overflow[v] += pushFlow;
flow[u][v] += pushFlow;
flow[v][u] -= pushFlow;
return true;
}
return false;
}
void relabel(int u) {
int minHeight = N;
for (auto v: G[u]) {
if (flow[u][v] < cap[u][v])
minHeight = min(minHeight, height[v]);
}
height[u] = minHeight + 1;
}
void preflowPush() {
height[1] = N;
for (auto v: G[1]) {
flow[1][v] = overflow[v] = cap[1][v];
flow[v][1] = -cap[1][v];
}
}
int main()
{
fin >> N >> M;
while(M--) {
int x, y, c;
fin >> x >> y >> c;
++x, ++y;
G[x].push_back(y);
G[y].push_back(x);
cap[x][y] = c;
}
preflowPush();
while (findVertex() != -1) {
int u = findVertex();
if (!push(u)) relabel(u);
}
fout << overflow[N] << "\n";
return 0;
}