Pagini recente » Cod sursa (job #760010) | Cod sursa (job #1239113) | Cod sursa (job #2286343) | Cod sursa (job #502546) | Cod sursa (job #2520238)
#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n,m;
int vf[5001],urm[5001],last[1001],nr;
bitset <1001> noSursa,noDest;
int flow[5001],sursa,dest;
int sum;
void adauga(int nod,int vec,int fl)
{
vf[++nr]=vec;
urm[nr]=last[nod];
last[nod]=nr;
flow[nr]=fl;
}
void getSursa()
{
for(int i=1;i<=n;i++)
if(noSursa[i]==0)
sursa=i;
else if(noDest[i]==0)
dest=i;
}
int vfA[10001],urmA[10001],lastA[1001],nrA;
int adrFlow[10001];
bitset <1001> viz;
queue <int> c;
void adaugaA(int nod,int vec,int adresa)
{
vfA[++nrA]=vec;
urmA[nrA]=lastA[nod];
lastA[nod]=nrA;
adrFlow[nrA]=adresa;
}
bool buildArb()
{
bool path=false;
nrA=0;
viz=0;
c.push(sursa);
viz[sursa]=1;
for(int i=1;i<=n;i++)
lastA[i]=0;
while(!c.empty())
{
int nod=c.front();
c.pop();
for(int k=last[nod];k;k=urm[k])
if(viz[ vf[k] ]==0 && flow[k])
{
viz[ vf[k] ]=1;
adaugaA(nod,vf[k],k);
adaugaA(vf[k],nod,k);
if(vf[k]==dest)
{
viz[ vf[k] ]=0;
path=true;
}
else
c.push(vf[k]);
}
}
return path;
}
int lista[1001],vr;
bool road(int nod,int from=0)
{
bool getOut=false;
if(nod==sursa)
return true;
for(int k=lastA[nod];k && !getOut;k=urmA[k])
if(vfA[k]!=from && flow[ adrFlow[k] ])
{
lista[++vr]=adrFlow[k];
getOut=road(vfA[k],nod);
if(!getOut)
vr--;
}
return getOut;
}
int main()
{
in>>n>>m;
for(int i,j,fl,k=1;k<=m;k++)
{
in>>i>>j>>fl;
adauga(i,j,fl);
noSursa[j]=1;
noDest[i]=1;
}
getSursa();
while(buildArb()==true)
{
vr=0;
while(road(dest)==true)
{
int minFound=flow[ lista[1] ];
for(int i=2;i<=vr;i++)
minFound=min(minFound, flow[ lista[i] ] );
for(int i=1;i<=vr;i++)
flow[ lista[i] ]-=minFound;
sum+=minFound;
vr=0;
}
}
out<<sum;
return 0;
}