Pagini recente » Cod sursa (job #2701029) | Cod sursa (job #1999083) | Cod sursa (job #2072090) | Agm 2018 Runda 1 | Cod sursa (job #1962369)
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#define NMAX 1005
using namespace std;
int x, y, c, tata[NMAX], N, M, solutie;
pair <int, int> mat[NMAX][NMAX];
queue <int> q;
vector <int> G[NMAX];
vector <int>::iterator it;
void read()
{
scanf("%d%d", &N, &M);
int x, y, c;
for(int i=1; i<=M; ++i)
{
scanf("%d%d%d", &x, &y, &c);
G[x].push_back(y);
G[y].push_back(x);
mat[x][y].first=c;
}
}
void reset(int x[], int nr)
{
for(int i=1; i<=nr; ++i)
x[i]=0;
}
bool bfs()
{
q.push(1);
tata[1]=1;
while(!q.empty())
{
int nod=q.front();
q.pop();
for(it=G[nod].begin(); it!=G[nod].end(); ++it)
{
if(tata[*it]==0 && mat[nod][*it].first-mat[nod][*it].second!=0)
{
q.push(*it);
tata[*it]=nod;
}
}
}
if(tata[N]==0)
return false;
return true;
}
void adaugareFlux(int x)
{
int aux=x;
int fluxMin=mat[x][N].first-mat[x][N].second;
while(tata[aux]!=aux)
{
int y=tata[aux];
int flux=mat[y][aux].first-mat[y][aux].second;
if(flux < fluxMin)
fluxMin=flux;
aux=tata[aux];
}
mat[x][N].second += fluxMin;
mat[N][x].second -= fluxMin;
while(tata[x]!=x)
{
aux=tata[x];
mat[aux][x].second +=fluxMin;
mat[x][aux].second -=fluxMin;
x=tata[x];
}
solutie+=fluxMin;
}
void solve()
{
while(bfs()==true)
{
for(it=G[N].begin(); it!=G[N].end(); ++it)
adaugareFlux(*it);
reset(tata, N);
}
}
int main()
{
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
read();
solve();
printf("%d", solutie);
return 0;
}