最小费用最大流模板(SPFA)

这篇博客详细介绍了如何运用 Dinic 算法解决图论中的最大流问题,通过 AC 代码展示了算法的具体实现,并提供了一个在线判题链接 P3381。文章还包含了 SPFA 短路径算法的使用,以及如何进行弧优化以提升效率。最终,代码成功求得最大流和最小割,并输出了结果。
摘要由CSDN通过智能技术生成

题目:https://www.luogu.com.cn/problem/P3381

AC代码:

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

typedef long long ll;

const int N = 10010,M = 500050;
const ll inf = ll(1e18);

struct edge{
	int next,to;
	ll w,c;
}edges[M];

int head[N],cur[N],vis[N],inq[N];
int cnt = 1;

ll dist[N];
int n,m,s,t;

void add(int u,int v,ll w,ll c){
	
	edges[++cnt].next = head[u];
	edges[cnt].to = v;
	edges[cnt].w = w;
	edges[cnt].c = c;
	head[u] = cnt;
}

bool SPFA(){
	
	fill(dist,dist+(n+1),inf);
	dist[s] = 0;
	
	queue<int> q;
	q.push(s);
	
	while(!q.empty()){
		
		int u = q.front();
		q.pop();
		inq[u] = 0;
		
		for(int i = head[u]; i;i = edges[i].next){
		
			int to = edges[i].to;
			ll w = edges[i].w;
			
			if(w > 0 && dist[to] > dist[u] + edges[i].c){
				
				dist[to] = dist[u] + edges[i].c;
				
				if(!inq[to]){
					inq[to] = 1;
					q.push(to);
				}	
			}
		}
	}

	return dist[t] != inf;
}

ll dfs(int p = s, ll flow = inf){
	
	if(p == t) return flow;
	
	ll rmn = flow;
	vis[p] = 1;
	for(int& i = cur[p]; i && rmn; i = edges[i].next){
		
		int to = edges[i].to;
		ll w = edges[i].w;
		
		if(w > 0 && !vis[to] && dist[to] == dist[p] + edges[i].c){
			
			ll f = dfs(to,min(rmn,w));
			rmn -= f;
			edges[i].w -= f;
			edges[i^1].w += f;
		}
	}
	vis[p] = 0;
	return flow - rmn;
}


pair<ll, ll> dinic(){
	
	pair<ll,ll> ans(0,0);
	
	while(SPFA()){
		
		memcpy(cur,head,sizeof(head));//弧优化 
		ll flow = dfs();
		ans.first += flow;
		ans.second += dist[t] * flow;
	}
	
	return ans;
}

int main(){
	
	ios_base::sync_with_stdio(false);
	
	cin >> n >> m >> s >> t;
	
	int u,v;
	ll w,c;
	for(int i = 1;i<=m;i++){
		cin >> u >> v >> w >> c;
		add(u,v,w,c);
		add(v,u,0,-c);
	}
	
	pair<ll,ll> ans = dinic();
	
	cout << ans.first << " " << ans.second << endl;
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值