Pagini recente » Cod sursa (job #3179003) | Cod sursa (job #2923055) | Cod sursa (job #468373) | Cod sursa (job #639623) | Cod sursa (job #1161417)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#define NMax 1001
using namespace std;
int n;
int cap[NMax][NMax];
int flux[NMax][NMax];
int tata[NMax];
vector <int> grr[NMax];//graf rezidual
queue <int> q;
bool bfs(int s)
{
int i;
for(i=1;i<=n;i++)
tata[i]=0;
tata[s]=s;
q.push(s);
while(!q.empty())
{
s=q.front();
q.pop();
for(i=0;i<grr[s].size();i++)
if((flux[s][grr[s][i]]<cap[s][grr[s][i]])&&(!tata[grr[s][i]]))
{
tata[grr[s][i]]=s;
q.push(grr[s][i]);
}
}
if(tata[n])//n=destinatie
return 1;
return 0;
}
int main()
{
int m;
int i;
int x,y,z;
int flow=0,fmin;
int vf;
ifstream f("maxflow.in");
f>>n>>m;
for(i=1;i<=m;i++)
{
f>>x>>y>>z;
cap[x][y]+=z;
grr[x].push_back(y);
grr[y].push_back(x);
}
f.close();
while(bfs(1))
{
for(i=0;i<grr[n].size();i++)
if((flux[grr[n][i]][n]<cap[grr[n][i]][n])&&(tata[grr[n][i]]))
{
vf=grr[n][i];
tata[n]=vf;
fmin=cap[vf][n]-flux[vf][n];
while(vf!=1)
{
fmin=min(fmin,cap[tata[vf]][vf]-flux[tata[vf]][vf]);
vf=tata[vf];
}
if(fmin>0)
{
vf=n;
while(vf!=1)
{
flux[tata[vf]][vf]+=fmin;
flux[vf][tata[vf]]-=fmin;
vf=tata[vf];
}
flow+=fmin;
}
}
}
ofstream g("maxflow.out");
g<<flow<<"\n";
g.close();
return 0;
}