POJ3255次短路

POJ3255

题意:给定一个图,求从1到n的次短路

分析:我们需要在dijkstra上作出一些修改,首先,到某个顶点v的次短路要么是到其他某个顶点u的最短路在加上u到v的边,要么是到v的次短路再加上u到v的边,因此我们需要记录的是最短和次短路。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <string>
 5 #include <vector>
 6 #include <algorithm>
 7 #include <set>
 8 #include <map>
 9 #include <bitset>
10 #include <cmath>
11 #include <queue>
12 #include <stack>
13 using namespace std;
14 const int maxn=5050;
15 const int INF=1<<30;
16 struct edge
17 {
18     int to,cost;  //顶点号和距离
19 };
20 typedef pair<int,int> P; //first是最短距离,second是顶点编号
21 vector<edge> g[maxn];
22 int n,r; //顶点数,边数
23 int d[maxn]; //最短距离
24 int d2[maxn]; //次短距离
25 void dijkstra(int s)
26 {
27     priority_queue<P, vector<P>, greater<P> > que;
28     fill(d,d+1+n,INF);
29     fill(d2,d2+1+n,INF);
30     d[s]=0;
31     que.push(P(0,s));
32 
33     while(!que.empty()){
34         P p=que.top(); que.pop();
35         int v=p.second,t=p.first;
36         if(d2[v]<t)  continue;
37         for(int i=0;i<g[v].size();i++){
38             edge e=g[v][i];
39             int dist=e.cost+t;
40             if(d[e.to]>dist){
41                 swap(d[e.to],dist);
42                 que.push(P(d[e.to],e.to));
43             }
44             if(d2[e.to]>dist&&d[e.to]<dist){
45                 d2[e.to]=dist;
46                 que.push(P(d2[e.to],e.to));
47             }
48         }
49     }
50 }
51 int main()
52 {
53     while(cin>>n>>r)
54     {
55         for(int i=0;i<r;i++)
56         {
57             int x,y,num;
58             scanf("%d%d%d",&x,&y,&num);
59             //无向图建图
60             edge e1;
61             e1.to=y,e1.cost=num;
62             g[x].push_back(e1);
63             edge e2;
64             e2.to=x,e2.cost=num;
65             g[y].push_back(e2);
66         }
67         dijkstra(1);
68         cout<<d2[n]<<endl;
69     }
70     return 0;
71 }
View Code

 

转载于:https://www.cnblogs.com/wolf940509/p/5589325.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值