• c++用dijkstra堆优化版求严格次短路(洛谷p2865)acwing(Tle)版本


    先看原题:

    贝茜把家搬到了一个小农场,但她常常回到 FJ 的农场去拜访她的朋友。贝茜很喜欢路边的风景,不想那么快地结束她的旅途,于是她每次回农场,都会选择第二短的路径,而不象我们所习惯的那样,选择最短路。
    贝茜所在的乡村有 R(1\le R \le 10^5)R(1≤R≤105) 条双向道路,每条路都联结了所有的 N(1\le N\le 5000)N(1≤N≤5000) 个农场中的某两个。贝茜居住在农场 11,她的朋友们居住在农场 NN(即贝茜每次旅行的目的地)。
    贝茜选择的第二短的路径中,可以包含任何一条在最短路中出现的道路,并且,一条路可以重复走多次。当然咯,第二短路的长度必须严格大于最短路(可能有多条)的长度,但它的长度必须不大于所有除最短路外的路径的长度。

    输出样例:

    1. 4 4
    2. 1 2 100
    3. 2 4 200
    4. 2 3 250
    5. 3 4 100

    输出样例:

    450

    Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)

    代码如下:

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. typedef pair<int, int> PII;
    6. const int N = 1e3 + 10, M = 2e5 + 10;
    7. int n, m;
    8. int dist1[N], dist2[N];
    9. int h[N], w[M], e[M], ne[M], idx;
    10. struct Ver
    11. {
    12. int to, di;
    13. bool operator< (const Ver &W) const
    14. {
    15. return di > W.di;
    16. }
    17. };
    18. void add(int a, int b, int c)
    19. {
    20. e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx;
    21. }
    22. int dijkstra()
    23. {
    24. memset(dist1, 0x3f, sizeof dist1);
    25. memset(dist2, 0x3f, sizeof dist2);
    26. priority_queue, greater> heap;
    27. heap.push({0, 1});
    28. dist1[1] = 0;
    29. while(heap.size())
    30. {
    31. auto t = heap.top();
    32. heap.pop();
    33. int ver = t.second, distance = t.first;
    34. if(distance > dist2[ver]) continue;
    35. for(int i =h[ver]; i != -1; i = ne[i])
    36. {
    37. int j =e[i];
    38. if(dist1[j] > distance + w[i])
    39. {
    40. dist2[j] = dist1[j];
    41. dist1[j] = distance + w[i];
    42. heap.push({dist1[j], j});
    43. }
    44. else if(dist2[j] > distance + w[i] && distance + w[i] > dist1[j])
    45. {
    46. dist2[j] = distance + w[i];
    47. heap.push({dist2[j], j});
    48. }
    49. }
    50. }
    51. return dist2[n];
    52. }
    53. int main()
    54. {
    55. scanf("%d%d", &n, &m);
    56. memset(h, -1, sizeof h);
    57. while (m--)
    58. {
    59. int a, b, c;
    60. scanf("%d%d%d", &a, &b, &c);
    61. add(a, b, c), add(b, a, c);
    62. }
    63. printf("%d\n", dijkstra());
    64. return 0;
    65. }

    1、有双向边,所以建图的时候要注意

    2、初始化链表

    3、使用结构体存储出发点和距离

    4、初始化最短路和次短路的数组

    5、要是实际距离比次短路都要长,就不加入队列中去

    6、最重要的一步

          要是当前新加入的点比最短路还要短,就先吧次短路更新为当前的最短路,再把最短路更新, 

          这样就不会出错了,如果新加入的点比次短路短但是比最短路长,更新次短路

    要是有在acwing学习的友友们知道怎么优化,麻烦评论以下了

  • 相关阅读:
    机组 CPU
    国内新闻媒体排行,如何邀约媒体现场造势?
    第二章Java概述
    二、【redux】redux 完整版求和Demo
    C++栈、队列、优先级队列模拟+仿函数
    HTTP/超文本传输协议(Hypertext Transfer Protocol)及HTTP协议通信步骤介绍和请求、响应阶段详解;
    VUE(递归)语法没错,但报 ESLint: ‘formatToTree‘ is not defined.(no-undef)
    初探富文本之React实时预览
    一文讲清楚密评中的数据库存储加密 安当加密
    1521_AURIX TC275 FPI总线系统寄存器
  • 原文地址:https://blog.csdn.net/2301_76180325/article/details/133015138