跳到正文

个人记录

模板:最小费用最大流(链式前向星)

wukaichen888约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月15日
收录
2025年12月12日
更新
2026年10月11日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll N=1e4+5,M=1e6+5,inf=1e18;
int n,m,s,t;
int tot1=1,head1[N],to[M],nxt[M],las[N];
ll w1[M],d1[N],c1[M],cst;
bool vis[N];
char *p1,*p2,buf[10000005];
#define nc() getchar()
ll read(){
	ll x=0,f=1;char ch=nc();
	while(ch<48||ch>57){if(ch=='-')f=-1;ch=nc();}
	while(ch>=48&&ch<=57){x=x*10+ch-48,ch=nc();}
	return x*f;
}
void add1(int u,int v,ll w,ll cost){to[++tot1]=v;nxt[tot1]=head1[u],w1[tot1]=w,c1[tot1]=cost,head1[u]=tot1;}
void add2(int u,int v,ll w,ll cost){add1(u,v,w,cost),add1(v,u,0,-cost);}
bool bfs(){
	queue<int>q;
	for(int i=1;i<=n;i++) d1[i]=inf,vis[i]=0,las[i]=head1[i];
	q.push(s),d1[s]=0,vis[s]=1;
	while(!q.empty()){
		int u=q.front();
		q.pop(),vis[u]=0;
		for(int i=head1[u];i>1;i=nxt[i])
			if(d1[to[i]]>d1[u]+c1[i]&&w1[i]){
				d1[to[i]]=d1[u]+c1[i];
				if(!vis[to[i]]) vis[to[i]]=1,q.push(to[i]);
			}
	}
	return d1[t]!=inf;
}
ll dfs(int u,ll p){
	if(u==t) return p;
	vis[u]=1;
	ll pos=p,h;
	for(int i=las[u];i;i=las[u]=nxt[las[u]])
		if(!vis[to[i]]&&d1[to[i]]==d1[u]+c1[i]&&w1[i]){
			h=dfs(to[i],min(w1[i],pos));
			if(h){
				cst+=h*c1[i];
				w1[i]-=h;
				w1[i^1]+=h;
				pos-=h;
			}
			else d1[to[i]]=inf;
			if(!pos) break;
		}
	vis[u]=0;
	return p-pos;
}
ll Dinic(){
	ll res=0;
	while(bfs()) res+=dfs(s,inf);
	return res;
}
int main(){
	n=read(),m=read(),s=1,t=n;
	for(ll i=1,u,v,w,cost;i<=m;i++)
		u=read(),v=read(),w=read(),cost=read(),
		add2(u,v,w,cost);
	printf("%lld ",Dinic());
	return printf("%lld\n",cst),0;
}
原文