1. 程式人生 > >POJ 3463 Sightseeing

POJ 3463 Sightseeing

註意讀題 mem 復雜度 ase names prior 狀態 tchar stc

次短路計數。

類似於最短路計數 + 次短路,在跑最短路的時候同時維護最短路,次短路,最短路的條數,次短路的條數,每一次更新在權值相同的地方計數。

要把(點,最/次短路)的二元組壓成一個狀態,每一次取出一個狀態去擴展,一共有$4$種情況,具體實現可以參照代碼。

$dij$或者$spfa$實現均可,這題數據很小,不帶堆優化也可以。

註意讀題,要在次短路$-1$$==$最短路的時候加入次短路的條數到答案中去。

時間復雜度$O(nlogn)$。

Code:

技術分享圖片
#include <cstdio>
#include <cstring>
#include <queue>
using
namespace std; const int N = 1005; const int M = 10005; int testCase, n, m, tot = 0, head[N]; int dis1[N], cnt1[N], dis[N][2], cnt[N][2]; bool vis[N][2]; struct Edge { int to, nxt, val; } e[M]; inline void add(int from, int to, int val) { e[++tot].to = to; e[tot].val = val; e[tot].nxt
= head[from]; head[from] = tot; } inline void read(int &X) { X = 0; char ch = 0; int op = 1; for(; ch > 9|| ch < 0; ch = getchar()) if(ch == -) op = -1; for(; ch >= 0 && ch <= 9; ch = getchar()) X = (X << 3) + (X << 1
) + ch - 48; X *= op; } struct Node { int now, s, d; inline Node(int nowNode, int sta, int dist) { now = nowNode, s = sta, d = dist; } friend bool operator < (const Node &x, const Node &y) { return x.d > y.d; } }; priority_queue <Node> Q; void dij(int st) { memset(dis, 0x3f, sizeof(dis)); memset(cnt, 0, sizeof(cnt)); memset(vis, 0, sizeof(vis)); Q.push(Node(st, 0, 0)); dis[st][0] = 0, cnt[st][0] = 1; for(; !Q.empty(); ) { int x = Q.top().now, s = Q.top().s; Q.pop(); if(vis[x][s]) continue; vis[x][s] = 1; for(int i = head[x]; i; i = e[i].nxt) { int y = e[i].to; if(dis[y][0] > dis[x][s] + e[i].val) { dis[y][1] = dis[y][0], cnt[y][1] = cnt[y][0]; dis[y][0] = dis[x][s] + e[i].val; cnt[y][0] = cnt[x][s]; Q.push(Node(y, 0, dis[y][0])), Q.push(Node(y, 1, dis[y][1])); } else if(dis[y][0] == dis[x][s] + e[i].val) { cnt[y][0] += cnt[x][s]; } else if(dis[y][1] > dis[x][s] + e[i].val) { dis[y][1] = dis[x][s] + e[i].val; cnt[y][1] = cnt[x][s]; Q.push(Node(y, 1, dis[y][1])); } else if(dis[y][1] == dis[x][s] + e[i].val) cnt[y][1] += cnt[x][s]; } } } int main() { for(read(testCase); testCase--; ) { read(n), read(m); tot = 0; memset(head, 0, sizeof(head)); for(int x, y, v, i = 1; i <= m; i++) { read(x), read(y), read(v); add(x, y, v); } int st, ed; read(st), read(ed); dij(st); int ans = cnt[ed][0]; if(dis[ed][1] - 1 == dis[ed][0]) ans += cnt[ed][1]; printf("%d\n", ans); } return 0; }
View Code

POJ 3463 Sightseeing