Pagini recente » Cod sursa (job #447720) | Cod sursa (job #2537743) | Cod sursa (job #961798) | Cod sursa (job #2132274) | Cod sursa (job #1759810)
#include <bits/stdc++.h>
using namespace std;
#define FILE_IO
int N, M;
int h[1005], e[1005];
int cp[1005][1005];
vector <int> edg[1005];
queue <int> q;
int inq[1005];
void addEdge(int x, int y, int cap)
{
if(cp[x][y] == 0 && cp[y][x] == 0)
{
edg[x].push_back(y);
edg[y].push_back(x);
}
cp[x][y] += cap;
}
void push(int x, int y)
{
if(h[x] != h[y] + 1) return;
if(!e[x]) return;
if(!cp[x][y]) return;
int add = min(e[x], cp[x][y]);
if(!inq[y])
q.push(y), inq[y] = 1;
e[x] -= add;
e[y] += add;
cp[x][y] -= add;
cp[y][x] += add;
}
void relabel(int nod)
{
int hmin = 2 * N;
for(auto nxt: edg[nod])
if(cp[nod][nxt])
hmin = min(hmin, h[nxt]);
h[nod] = hmin + 1;
}
void discharge(int nod)
{
for(auto nxt: edg[nod])
push(nod, nxt);
if(e[nod])
relabel(nod);
else
q.pop(), inq[nod] = 0;
}
int getMaxFlow(int s, int t)
{
inq[s] = inq[t] = 1;
h[s] = 1;
for(auto nxt: edg[s])
{
e[s] += cp[s][nxt];
push(s, nxt);
}
h[s] = N;
while(!q.empty())
{
int nod = q.front();
discharge(nod);
}
return e[t];
}
int main()
{
#ifdef FILE_IO
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
#endif
scanf("%d%d", &N, &M);
memset(cp, 0, sizeof(cp));
for(int i = 1; i <= M; i++)
{
int x, y, cap;
scanf("%d%d%d", &x, &y, &cap);
addEdge(x, y, cap);
}
int ans = getMaxFlow(1, N);
printf("%d\n", ans);
return 0;
}