关于 SPFA 跑得奇慢无比
查看原帖
关于 SPFA 跑得奇慢无比
563650
haochengw920楼主2024/3/3 18:37

rt,EK + SPFA,看了题解区感觉复杂度差不多

TLE on # 8, 9, 10 ,本地跑了 203s ,答案正确

#include<cstdio>
#include<cctype>
#include<algorithm>
#define R register
#define INF 0x3f3f3f3f
using namespace std;

inline int read() {
	R int x = 0; char c = getchar();
	while (!isdigit(c)) c = getchar();
	while (isdigit(c)) x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
	return x;
}

const int MAXN = 5005, MAXM = 50005;

int n, m, st, nd;
struct edge {
	int to, nex, fl, cst;
}e[MAXM << 1]; int idx = 1, head[MAXN];
inline void add(R int u, R int v, R int w, R int c) {
	e[++ idx].to = v; e[idx].nex = head[u];
	e[idx].fl = w; e[idx].cst = c;
	head[u] = idx;
}

int dis[MAXN];
int top, q[MAXN];
int pre[MAXN], pdg[MAXN];
inline bool SPFA() {
	for (R int i = 1; i <= n; ++ i)
		dis[i] = INF;
	dis[st] = 0; q[++ top] = st;
	while (top) {
		R int u = q[top --]; 
		for (R int i = head[u]; i; i = e[i].nex) {
			R int v = e[i].to;
			if (!e[i].fl || dis[v] <= dis[u] + e[i].cst)
				continue;
			dis[v] = dis[u] + e[i].cst;
			pre[v] = u, pdg[v] = i;
			q[++ top] = v; 
		}
	}
	return dis[nd] != INF;
}
int ans1, ans2;
inline void EK() {
	while (SPFA()) {
		R int x = nd, mf = INF;
		while (x != st) 
			mf = min(mf, e[pdg[x]].fl), 
			x = pre[x];
		x = nd;
		while (x != st) 
			e[pdg[x]].fl -= mf, 
			e[pdg[x] ^ 1].fl += mf, 
			x = pre[x];
		ans1 += mf; ans2 += dis[nd] * mf;
	}
}

int main()
{
	n = read(), m = read(), st = read(), nd = read();
	for (R int i = 1; i <= m; ++ i) {
		R int u = read(), v = read(), w = read(), c = read();
		add(u, v, w, c); add(v, u, 0, -c);
	}
	EK();
	return printf ("%d %d\n", ans1, ans2), 0;
}
2024/3/3 18:37
加载中...