下面这个代码是给普通spfa,我本想用它来测试spfa面对高压数据下的表现,但是让人困惑的是洛谷的评测机给出了WA的评分,这让我以为是算法哪里除了问题,检查半天没检查出来,发到群里,有人指出这是手写队列导致溢出,这一点我一开始是想到了的,我没想到溢出导致了WA,这里记录一下,以后记得溢出也会WA
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define Max 500000
#define Inf (0x7fffffff/2)
int first0[Max + 1], next0[Max + 1];
int v[Max + 1], w[Max + 1];
int dist[Max + 1], book[Max + 1];
int queue[Max + 1],head=0,tail=0;
int read() {
int x = 0, f = 1; char c = getchar();
while (c < '0' || c > '9') { if (c == '-')f = -1; c = getchar(); }
while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = getchar(); }
return x * f;
}
int main()
{
int N, M, S; cin >> N >> M >> S;
//初始化邻接表
for (int i = 1; i <= M; i++){
first0[i] = next0[i] = -1;
}
//初始化dist
for (int i = 1; i <= N; i++){
dist[i] = Inf;
}
//读入边
/*
5 5 1
2 3 2 1 2 -3 1 5 5 4 5 2 3 4 3
*/
register int u;
for (int i = 1; i <= M; i++){
u = read(), v[i] = read(), w[i] = read();
next0[i] = first0[u];
first0[u] = i;
}
//spfa
dist[S] = 0;
book[S] = 1;
queue[tail++] = S;
while (head != tail) {
int k = queue[head++];
for (int e = first0[k]; e!=-1; e=next0[e]){
if (dist[k] + w[e] < dist[v[e]]) {
dist[v[e]] = dist[k] + w[e];
if (!book[v[e]]) {
//if (head != tail && v[k] < queue[head] && head>=1) {
// queue[--head] = v[k];
//}
queue[tail++] = v[e];
book[v[e]] = 1;
}
}
}
book[k] = 0;
}
//output
for (int i = 1; i <= N; i++){
if(dist[i]!=Inf)
printf("%d ", dist[i]);
else printf("%d ",0x7fffffff);
}
return 0;
}