跳到正文

个人记录

最大流板子

jinhungqian约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月12日
收录
2026年8月12日
更新
2026年11月17日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+5;
int n,m,s,t,head[N],nxt[N<<2],w[N<<2],to[N<<2],cur[N],dep[N];
const int inf=2e9;
int tot;
bool bfs(){
	memset(dep,0,sizeof(dep));
	dep[s]=1;
	queue<int> q;
	q.push(s);
	while(!q.empty()){
		int u=q.front();
		q.pop();
		cur[u]=head[u];
		for(int i=head[u];~i;i=nxt[i]){
			int v=to[i];
			if(!w[i]||dep[v]>0) continue;
			dep[v]=dep[u]+1;
			q.push(v);
		}
	}
	return dep[t]!=0;
}
ll dfs(int u,ll flow){
	if(u==t) return flow;
	ll maxflow=0;
	for(int i=cur[u];~i;i=nxt[i]){
		cur[u]=i;
		int v=to[i],k=min(w[i]*1ll,flow);
		if(dep[v]==dep[u]+1&&k){
			ll nx=dfs(v,k);
			maxflow+=nx;
			flow-=nx;
			w[i]-=nx;
			w[i^1]+=nx;
			if(flow==0) break;
		}
	}
	return maxflow;
}
ll dinic(){
	ll maxflow=0;
	while(bfs()){
		maxflow+=dfs(s,inf);
	}
	return maxflow;
}
void add(int u,int v,int wi){
	nxt[++tot]=head[u];
	w[tot]=wi;
	to[tot]=v;
	head[u]=tot;
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	memset(head,-1,sizeof(head));
	tot=-1;
	cin>>n>>m>>s>>t;
	for(int i=1;i<=m;i++){
		int u,v,w;
		cin>>u>>v>>w;
		add(u,v,w);
		add(v,u,0);
	}
	cout<<dinic();
	return 0;
}
原文