萌新60求助网络流
查看原帖
萌新60求助网络流
308439
__mcx_楼主2022/4/8 17:51

甚至没有瞎交的最大流模板分高(

#include<bits/stdc++.h>
#define ll long long
inline ll read(){
	ll w=1,s=0;char ch=getchar();
	while(ch<'0'||ch>'9') w=(ch=='-'?-1:1),ch=getchar();
	while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
	return s*w;
}
const int nn= 3e6+10;
ll n,m,a,b,c,ans;
ll e[nn],h[nn],cnt=1,w[nn],nt[nn];
void add(ll u,ll v,ll val){
	e[++cnt]=v;
	w[cnt]=val;
	nt[cnt]=h[u];
	h[u]=cnt;
}
ll dep[nn],q[nn],cur[nn];
ll st,ed;
const ll maxn = 1<<30;
bool bfs(){
	for(int i=0;i<=n;i++) dep[i]=0;
	q[1]=st;dep[st]=1;
	cur[st]=h[st];
	ll hd=0,tl=1;
	while(hd!=tl){
		ll u=q[++hd];
		for(int i=h[u];i;i=nt[i]){
			ll v=e[i];
			if(w[i]&&!dep[v]){
				cur[v]=h[v];
				dep[v]=dep[u]+1;
				q[++tl]=v;
				if(v==ed) return 1;
			}
		}
	}
	return 0;
}
ll dfs(ll u,ll fl){
	if(u==ed) return fl;
	ll out=0;
	for(ll i=cur[u];i&&fl;i=nt[i]){
		ll v=e[i];cur[u]=i;
		if(w[i]&&dep[v]==dep[u]+1){
			ll res=dfs(v,(w[i]<fl?w[i]:fl));
			w[i]-=res;
			w[i^1]+=res;
			fl-=res;
			out+=res;
		}
	}
	if(out==0) dep[u]=0;
	return out;	 
}
using namespace std;
int main(){
	n=read(),m=read(),st=read(),ed=read();
	for(int i=1;i<=n;i++) add(i,i+n,1),add(i+n,i,0);
	for(int i=1;i<=m;i++){
		a=read(),b=read();
		add(a+n,b,maxn);
		add(a,b+n,0);
		add(b+n,a,maxn);
		add(b,a+n,0);
	}
	ll x;
	st+=n;
	while(bfs()) while(x=dfs(st,maxn))ans+=x;
	printf("%lld\n",ans);
	return 0;
}
2022/4/8 17:51
加载中...