Pagini recente » Cod sursa (job #2558609) | Cod sursa (job #2459474) | Cod sursa (job #529254) | Cod sursa (job #2965696) | Cod sursa (job #3260823)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int N=1e4+5;
int n,m;
vector<int>edge[N];
bool viz[N];
int dst[N][N];
int ans, niv[N];
void bfs()
{
for( int i=1;i<=n;i++)
niv[i]=-1;
niv[1]=0;
queue<int>q;
q.push(1);
while(!q.empty())
{
int nod=q.front();
q.pop();
for(auto x : edge[nod])
if(niv[x]== -1 && dst[nod][x] > 0)
{
niv[x]=niv[nod]+1;
q.push(x);
if(x==n)
return;
}
}
}
int dfs(int nod,int minimum)
{
if (minimum ==0 || nod == n)
return minimum;
for(auto x: edge[nod])
if(dst[nod][x]>0 && niv[x] == niv[nod]+1)
{
int after = dfs(x, min(minimum, dst[nod][x]));
if( after > 0)
{
dst[nod][x] -= after;
dst[x][nod] += after;
return after;
}
}
return 0;
}
bool flux()
{
bfs();
if(niv[n] == -1) return 0;
int value = 0;
while(true)
{
int aux = dfs ( 1, 1e9);
if ( aux == 0)
break;
value += aux;
}
if(value==0)
return false;
ans += value;
return true;
}
int main()
{
f>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,z;
f>>x>>y>>z;
edge[x].push_back(y);
edge[y].push_back(x);
dst[x][y]=z;
}
while(flux());
g<<ans;
return 0;
}