Pagini recente » Cod sursa (job #1050485) | Cod sursa (job #1625965) | Cod sursa (job #31001) | Cod sursa (job #2800315) | Cod sursa (job #2705084)
#include <bits/stdc++.h>
#define min(a,b) a<b? a: b
using namespace std;
const int inf=INT_MAX;
const int nmax=5005;
struct edge
{
int x,y;
long long f,c;
};
int n,m,st,dr,lvl[nmax],viz[nmax];
long long lim,flow;
vector<edge> mch;
vector<int> adc[nmax];
queue<int> q;
void addedge(int x,int y,int c)
{
edge temp;
temp.x=x;
temp.y=y;
temp.c=c;
temp.f=0;
adc[x].push_back(mch.size());
mch.push_back(temp);
temp.x=y;
temp.y=x;
temp.c=0;
temp.f=0;
adc[y].push_back(mch.size());
mch.push_back(temp);
}
bool bfs()
{
while(!q.empty())
{
int nod=q.front();
q.pop();
for(int i=0; i<adc[nod].size(); ++i)
if((mch[adc[nod][i]].c-mch[adc[nod][i]].f>=1) && (lvl[mch[adc[nod][i]].y]==-1))
{
lvl[mch[adc[nod][i]].y]=lvl[nod]+1;
q.push(mch[adc[nod][i]].y);
}
}
return lvl[dr]!=-1;
}
int dfs(int nod,int f)
{
if(nod==dr)
return f;
for(int i=viz[nod];i<adc[nod].size();++i)
{
int u = mch[adc[nod][i]].y;
if(lvl[nod]+1!=lvl[mch[adc[nod][i]].y] || mch[adc[nod][i]].c-mch[adc[nod][i]].f<1)
continue;
long long ret=dfs(mch[adc[nod][i]].y,min(f,mch[adc[nod][i]].c-mch[adc[nod][i]].f));
if(ret==0)
continue;
mch[adc[nod][i]].f+=ret;
mch[adc[nod][i] ^ 1].f-=ret;
return ret;
}
return 0;
}
long long flux()
{
flow=0;
while(1)
{
for(int i=0; i<=n; ++i)
lvl[i]=-1;
lvl[st]=0;
q.push(st);
if(!bfs())
break;
for(int i=0; i<=n; ++i)
viz[i]=0;
while(long long ret=dfs(st,inf))
flow+=ret;
}
return flow;
}
int main()
{
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i)
{
int x,y,c;
scanf("%d%d%d",&x,&y,&c);
addedge(x,y,c);
}
st=1;dr=n;
printf("%lld",flux());
return 0;
}