求助csps初赛最后一题
查看原帖
求助csps初赛最后一题
726992
ccxswl楼主2024/9/21 21:31

抄下来了,过不了 hack,感觉这个代码能过这题。是我写错了吗,还是无向图有什么不一样的吗。

#include <bits/stdc++.h>

using namespace std;

int read() {
    int s = 0, w = 1;
    char c = getchar();
    while (!isdigit(c)) {
        if (c == '-')
            w = -w;
        c = getchar();
    }
    while (isdigit(c)) {
        s = s * 10 + c - 48;
        c = getchar();
    }
    return s * w;
}
void pr(int x) {
    if (x < 0)
        putchar('-'), x = -x;
    if (x > 9)
        pr(x / 10);
    putchar(x % 10 + 48);
}
#define end_ putchar('\n')
#define spc_ putchar(' ')

const int maxN = 5e3 + 7, maxM = 1e5 + 7;

int head[maxN], tot = 1;
struct edge {
	int ls, to, w;
	edge(int a = 0, int b = 0, int c = 0) {
		ls = a, to = b, w = c;
	}
} e[maxM * 2];
void add(int u, int v, int w) {
	e[++tot] = edge(head[u], v, w);
	head[u] = tot;
}

int n, m;

int dis[maxN * 2], pre[maxN * 2];
int *dis2, *pre2;
bool vis[maxN * 2];

using pq_p_ii = priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>;

bool upd(int a, int b, int d, pq_p_ii &q) {
	if (d >= dis[b])
		return false;
	if (b <= n)
		upd(pre[b], b + n, dis[b], q);
	q.push({d, b});
	dis[b] = d;
	pre[b] = a;
	return true;
}

void solve() {
	memset(dis, 0x3f, sizeof(dis));
	memset(pre, -1, sizeof(pre));
	dis2 = dis + n, pre2 = pre + n;
	static pq_p_ii q;
	dis[1] = 0;
	q.push({0, 1});
	while (!q.empty()) {
		int aa = q.top().second;
		q.pop();
		if (vis[aa])
			continue;
		vis[aa] = true;
		
		int a = aa > n ? aa - n : aa;
		for (int i = head[a]; i; i = e[i].ls) {
			int b = e[i].to, c = e[i].w;
			if (aa <= n) {
				if (!upd(a, b, dis[a] + c, q))
					upd(a, b + n, dis[a] + c, q);
			}
			else
				upd(a + n, b + n, dis2[a] + c, q);
		}
	}
}

int main() {
	n = read(), m = read();
	for (int i = 1; i <= m; i++) {
		int x = read(), y = read(), z = read();
		add(x, y, z);
		add(y, x, z);
	}
	solve();
	pr(dis2[n]), end_;
}

2024/9/21 21:31
加载中...