网络流
流网络: G=(V,E)是一个有向图,图中每条边(u,v)有一个非负的容量值c(u,v)>=0,
dicnic(n^2m)
#include<bits/stdc++.h>
using namespace std;
const int N=1e4+10;
const int M=2e5+10;
const int INF=0x3f3f3f3f;
int n,m,s,t;
int tot;
int head[N],ver[M],ne[M],w[M],cur[N],d[N];
void add(int x,int y,int z)
{
ver[tot]=y,ne[tot]=head[x],w[tot]=z,head[x]=tot++;
ver[tot]=x,ne[tot]=head[y],w[tot]=0,head[y]=tot++;
}
bool bfs()
{
memset(d,-1,sizeof(d));
d[s]=0;
queue<int>q;
q.push(s);
cur[s]=head[s];
while(q.size())
{
int x=q.front();q.pop();
for(int i=head[x];~i;i=ne[i])
{
int y=ver[i];
if(d[y]==-1&&w[i])
{
d[y]=d[x]+1;
cur[y]=head[y];
if(y==t) return 1;
q.push(y);
}
}
}
return 0;
}
int dfs(int x,int limit)
{
if(x==t) return limit;
int flow=0;
for(int i=cur[x];~i&&flow<limit;i=ne[i])
{
int y=ver[i];
cur[x]=i;
if(d[y]==d[x]+1&&w[i])
{
int c=dfs(y,min(limit-flow,w[i]));
if(!c) d[y]=-1;
w[i]-=c,w[i^1]+=c;
flow+=c;
}
}
return flow;
}
int dinic()
{
int res=0;
int f;
while(bfs()) while(f=dfs(s,INF)) res+=f;
return res;
}
int main(){
cin>>n>>m>>s>>t;
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
add(x,y,z);
}
printf("%d\n",dinic());
return 0;
}

浙公网安备 33010602011771号