题目描述

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 bidirectional roads, each linking two of the intersections, conveniently numbered . 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).

输入描述:

Line Two space-separated integers: and
Lines Each line contains three space-separated integers: and that describe a road that connects intersections  and and has length

输出描述:

Line 1: The length of the second shortest path between node 1 and node

示例1

输入
4 4
1 2 100
2 4 200
2 3 250
3 4 100
输出 
450
说明
Two routes: and

解答

题意:

求出1到n的次短路

题解:

首先考虑, 求到的次短路有两种方法
  1. 到达某个顶点u的最短路
  2. 到达的次短路
很显然我们不仅需要存最短距离, 也要存一下此段距离
仔细考虑, 第二种情况可能和第一种情况冲突.
因为的更新是同步的, 所以共用一个队列就好了

经验小结:

对最短路的改写要先考虑清楚思路, 改写一定要全面, 但尽可能不必增添新的步骤
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const LL maxn = 5010;
const int inf = 1<<30;

int N, M;
struct node{
    int v, w; //目标节点和权值
    node(int vv, int ww){v = vv, w = ww;}
};
vector<node> G[maxn];
int d1[maxn], d2[maxn]; //最短路和次短路
typedef pair<int, int> P;

int dijkstra(){
    fill(d1, d1+maxn, inf);
    fill(d2, d2+maxn, inf);
    priority_queue<P, vector<P>, greater<P> > q; //d1,d2共用队列
    d1[1] = 0;                                   //d2[1]不应初始化为0
    q.push(P(d1[1], 1));

    while(!q.empty()){
        P cur = q.top();
        q.pop();
        int d = cur.first, u = cur.second;

        if(d2[u] < d) continue; //直接跳过
        for(int i = 0; i < G[u].size(); i++){
            node &e = G[u][i];
            int td = d+e.w;     //假设为第一种情况
            if(d1[e.v] > td){   //恰好和第二种情况冲突
                swap(td, d1[e.v]);
                q.push(P(d1[e.v], e.v));
            }
            if(td<d2[e.v] && td>d1[e.v]){ //更新d2
                d2[e.v] = td;
                q.push(P(d2[e.v], e.v));
            }
        }
    }

    return d2[N];
}
int main()
{
    int u, v, w;
    cin >> N >> M;
    while(M--){
        cin >> u >> v >> w;
        G[u].push_back(node(v, w)), G[v].push_back(node(u, w));
    }
    cout << dijkstra() << endl;

	return 0;
}

来源:Suprit