Pagini recente » Cod sursa (job #1950409) | Cod sursa (job #1973101) | Cod sursa (job #2577137) | Cod sursa (job #2676497) | Cod sursa (job #2497523)
#include <bits/stdc++.h>
using namespace std;
struct Dinic
{
struct edge
{
int flow,to,next;
};
vector<edge>edges;
vector<int>adia,at,dist;
int s,d;
void addedge(int from,int to,int cap)
{
edges.push_back({cap,to,adia[from]});
adia[from]=edges.size()-1;
edges.push_back({0,from,adia[to]});
adia[to]=edges.size()-1;
}
bool bfs()
{
fill(dist.begin(),dist.end(),1e9);
queue<int>q;dist[s]=0;
q.push(s);
while(!q.empty())
{ int i;
int x=q.front();q.pop();
for(i=adia[x];i!=-1;i=edges[i].next)
{
int to=edges[i].to;
if(dist[to]>dist[x]+1&&edges[i].flow)
{
dist[to]=dist[x]+1;
q.push(to);
}
}
}
return dist[d]<1e9;
}
int dfs(int nod,int flux)
{
if(nod==d)return flux;
while(at[nod]!=-1)
{
int f;
edge &e=edges[at[nod]];
if(dist[e.to]==dist[nod]+1&&e.flow&&(f=dfs(e.to,min(flux,e.flow))))
{
e.flow-=f;
edges[at[nod]^1].flow+=f;
return f;
}
at[nod]=edges[at[nod]].next;
}
return 0;
}
int GetFlow()
{
int f=0;
while(bfs())
{
at=adia;
int x=dfs(s,1e9);
while(x)
{
f+=x;
x=dfs(s,1e9);
}
}
return f;
}
Dinic(int n,int s1,int d1)
{
s=s1;
d=d1;
at=adia=dist=vector<int>(n+2,-1);
}
};
int main()
{
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
int n,m;
cin>>n>>m;
Dinic g(n,1,n);
for(int i=1;i<=m;i++)
{
int a,b,c;
cin>>a>>b>>c;
g.addedge(a,b,c);
}
int res=g.GetFlow();
cout<<res;
return 0;
}