Pagini recente » Cod sursa (job #1629586) | Cod sursa (job #3337119) | Cod sursa (job #601251) | Cod sursa (job #3337216) | Cod sursa (job #3338012)
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n, m, x, y, c, mat[1005][1005], fr[1005], nvl[1005], ans, finn, sursa;
vector <int> v[1005];
void bfs(int nod)
{
for(int i=1; i<=n; i++)
{
fr[i]=0;
nvl[i]=-1;
}
queue <int> q;
q.push(nod);
nvl[nod]=0;
while(!q.empty())
{
int x=q.front();
q.pop();
for(auto i: v[x])
{
if(mat[x][i]>0 && nvl[i]==-1)
{
nvl[i]=nvl[x]+1;
q.push(i);
}
}
}
}
int dfs(int nod, int minf)
{
if(nod==finn || minf==0)
return minf;
while(fr[nod]<v[nod].size())
{
int k=v[nod][fr[nod]];
if(mat[nod][k]>0 && nvl[nod]+1==nvl[k])
{
int x=dfs(k, min(minf, mat[nod][k]));
if(x>0)
{
mat[nod][k]-=x;
mat[k][nod]+=x;
return x;
}
else
fr[nod]++;
}
else
fr[nod]++;
}
return 0;
}
bool flux(int nod)
{
bfs(nod);
if(nvl[finn]==-1)
return 0;
else
{
int val=0, x=1;
while(x)
{
x=dfs(1, 1e9);
val+=x;
}
ans+=val;
return (val!=0);
}
}
int main()
{
fin>>n>>m;
for(int i=1; i<=m; i++)
{
fin>>x>>y>>c;
mat[x][y]=c;
v[x].push_back(y);
v[y].push_back(x);
}
sursa=1, finn=n;
while(flux(sursa));
fout<<ans;
return 0;
}