1. 程式人生 > >記錄一個洛谷評測機上的問題

記錄一個洛谷評測機上的問題

下面這個程式碼是給普通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; }