【模板】最大流 加强版 / 预流推进

题目跳转

代码

#include<bits/stdc++.h>
using namespace std;
typedef int ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
    ll x=0,f=1,ch=gc();
    while(ch!=EOF&&(ch<'0'||ch>'9')){
        if(ch=='-'){
        	f=-1;
		}
        ch=gc();
    }
	if(ch==EOF){
		return x;
	}
    while(ch>='0'&&ch<='9'){
        x=(x<<1)+(x<<3)+(ch-'0');
        ch=gc();
    }
    return x*f;
}
uint8_t obuf[1<<20],*op=obuf;
#define fls() (fwrite(obuf,1,op-obuf,stdout),op=obuf,0)
#define pc(ch) (op==obuf+(1<<20)?fls():0,*op++=(ch))
void write(ll x){
    if(x<0){
		x=-x;
		pc('-');
	}
    if(x>9){
    	write(x/10);
	}
    pc(x%10+'0');
}
const ll maxm=1.2e5+5,maxn=1.2e3+5,inf=1e9;
ll n,m,s,t,ecnt=1,head[maxn],now[maxn],dis[maxn],ans,mp[maxn][maxn];
queue<ll> q;
struct node{
	ll nxt,to,val;
}e[maxm<<1];
void adde(ll u,ll v,ll w){
	e[++ecnt].nxt=head[u];
	e[ecnt].to=v;
	e[ecnt].val=w;
	head[u]=ecnt;
}
bool bfs(){
	q=queue<ll>();
	for(ll i=1;i<=n;i++){
		dis[i]=inf;
	}
	q.push(s);
	dis[s]=0;
	now[s]=head[s];
	while(!q.empty()){
		ll x=q.front();
		q.pop();
		for(ll i=head[x];i;i=e[i].nxt){
			ll y=e[i].to;
			if(e[i].val>0&&dis[y]==inf){
				now[y]=head[y];
				dis[y]=dis[x]+1;
				if(y==t){
					return true;
				}
				q.push(y);
			}
		}
	}
	return false;
}
ll dfs(ll x,ll sum){
	if(x==t){
		return sum;
	}
	ll k,res=0;
	for(ll i=now[x];i&&sum;i=e[i].nxt){
		now[x]=i;
		ll y=e[i].to;
		if(e[i].val>0&&dis[y]==dis[x]+1){
			k=dfs(y,min(sum,e[i].val));
			if(k==0){
				dis[y]=inf;
			}else{
				e[i].val-=k;
				e[i^1].val+=k;
				res+=k;
				sum-=k;
			}
		}
	}
	return res;
}
int main(){
	n=rd();
	m=rd();
	s=rd();
	t=rd();
	for(ll i=1;i<=m;i++){
		ll u=rd(),v=rd(),w=rd();
		mp[u][v]+=w;
	}
	for(ll i=28;i>=0;i-=4){
		for(ll u=1;u<=n;u++){
			for(ll v=u+1;v<=n;v++){
				if((mp[u][v]>0||mp[v][u]>0)&&(mp[u][v]>=(1<<i)||mp[v][u]>=(1<<i))){
					adde(u,v,mp[u][v]);
					adde(v,u,mp[v][u]);
					mp[u][v]=0;
					mp[v][u]=0;
				}
			}
		}
		while(bfs()){
			ans+=dfs(s,inf);
		}
	}
	write(ans);
    fls();
    return 0;
}
posted @ 2026-11-16 17:35  beiciqi  阅读(5)  评论(0)    收藏  举报