MnZn 求助多路增广费用流
查看原帖
MnZn 求助多路增广费用流
551861
strcmp楼主2022/3/23 16:40

rt,蜜汁 MLE 最后四个点。

#include <bits/stdc++.h>
using namespace std;
#define inf 1000000000000000
#define V 100010
#define E 5000010
typedef long long int ll;
struct edge {
	int to, next;
	ll capa,cost;
};
int cnt = 0, head[V], n, m; edge node[E];
inline void add(int fir, int nxt, ll w, ll c) {
	node[cnt].to = nxt,
	node[cnt].capa = w,
	node[cnt].cost = c,
	node[cnt].next = head[fir],
	head[fir] = cnt++;
}
int s, t, gap[V], cur[V]; queue<int>que; ll dep[V], sum = 0, cost = 0;
inline bool spfa(){
	for(int i=1;i <= n;i++)dep[i]=inf;
	dep[s] = 0; que.push(s); int u, v;
	while(!que.empty()){
		v = que.front(); que.pop();
		for(register int i = head[v]; i != -1; i = node[i].next){
			u = node[i].to;
			if(node[i].capa && dep[v] + node[i].cost < dep[u]){
				dep[u] = dep[v] + node[i].cost;
				que.push(u);
			}
		}
	}
	return (dep[t] != inf);
}
ll dfs(int v,ll flow){
	if(v == t || flow == 0)return flow; ll used = 0, wei = 0, c = 0;
	for(register int i = cur[v]; i != -1; i = node[i].next){
		cur[v] = i;
		if(dep[node[i].to] == dep[v] + node[i].cost && node[i].capa){
			wei = dfs(node[i].to, min(flow - used, node[i].capa)); 
			if(wei){
				used += wei;
				node[i].capa -= wei;
				node[i ^ 1].capa += wei;
				cost += node[i].cost * wei;
			}
		}
		if(used == flow)return used;
	}
	return used;
}
void Dinic(){
	while(spfa()){
		memcpy(cur,head,(n + 1)*sizeof(int));
		sum += dfs(s, inf);
	}
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(); cout.tie();
	memset(head, -1, V * sizeof(int));
	cin >> n >> m >> s >> t;
	int f, l; ll w, c;
	for (register int i = 0; i < m; i++) {
		cin >> f >> l >> w >> c;
		add(f, l, w, c);
		add(l, f, 0, -c);
	}
	Dinic();
	cout<<sum<<" "<<cost;
	return 0;
}
2022/3/23 16:40
加载中...