题解 : https://xiaoxiaoh.blog.csdn.net/article/details/104238138
一、内容
Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
Input
Line 1: Two space-separated integers: N and R
Lines 2.. R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)
Output
Line 1: The length of the second shortest path between node 1 and node N
Sample Input
4 4
1 2 100
2 4 200
2 3 250
3 4 100
Sample Output
450
二、思路
- 每个节点有2种状态。 0 代表最短路, 1代表次短路。
- 通过djkstra的思路, 当某个点的状态发生改变,那么就将该点进行入队。每次从队列里面找出距离最短的进行更新其他节点。每个状态只会出队一次。
- 所以若求出的路径小于该点已经求得的最短路, 那么让次短路等于之前的最短路, 最短路等于新求出的路径。 这时候有2个节点状态改变所以2个节点入队。
三、代码
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 5005, M = 2e5 + 5;
struct E {
int v, w, next;
} e[M];
struct Node {
int v, d, st; //st代表这个节点的状态
Node(int d, int v, int st): d(d), v(v), st(st){}
bool operator < (const Node&o) const {
return d > o.d;
}
};
int n, m, len, u, v, w, h[N], d1[N], d2[N];
bool vis[N][2]; //2种状态 0代表最短路 1代表次短路
void add(int u, int v, int w) {
e[++len].v = v; e[len].w = w; e[len].next = h[u]; h[u] = len;
}
void djkstra() {
memset(d1, 0x3f, sizeof(d1));
memset(d2, 0x3f, sizeof(d2));
d1[1] = 0; //最开始次短路没有 所以d2不用更新
priority_queue<Node> q;
q.push(Node(0, 1, 0));
while (!q.empty()) {
Node t = q.top();
q.pop();
int u = t.v, st = t.st;
if (vis[u][st]) continue; //最短路贪心的思想 每种状态节点遍历一次
vis[u][st] = true;
for (int j = h[u]; j; j = e[j].next) {
int v = e[j].v;
int w = e[j].w + t.d;
if (w < d1[v]) {
d2[v] = d1[v];
d1[v] = w;
q.push(Node(d2[v], v, 1)); //因为它的状态改变了 所以也要入队
q.push(Node(d1[v], v, 0)); //0代表以最短路状态入队
} else if (w < d2[v] && d1[v] < w) {//严格最短路 次短路不能和最短路相同
d2[v] = w;
q.push(Node(d2[v], v, 1));
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
add(u, v, w); add(v, u, w);
}
djkstra();
printf("%d\n", d2[n]);
return 0;
}
兄弟你这是spfa啊