POJ 3255 Roadblocks(次短路)

5 篇文章 0 订阅
3 篇文章 0 订阅

题目链接:点击打开链接

起点到某个顶点v的次短路要么是到某个顶点u的最短路加上(u,v),要么是到u的次短路加上(u,v),因此需要记录所有起点到其它点的次短路与最短路

这里使用STL和图的邻接表+迪杰斯特拉来实现

AC代码如下:

#include <iostream>
#include <cstring>
#include <queue>
#include <vector>

using namespace std;
#define MAXN_V 5005
#define INF  1000000000

struct edge{
    int to, cost;
    edge(int t, int c):to(t), cost(c){}
};
typedef pair<int, int> P;
int N, R;

vector<edge> Gra[MAXN_V];

int d[MAXN_V];
int d2[MAXN_V];

void dijkstra(int s)
{
    priority_queue<P, vector<P>, greater<P> > que;
    fill(d, d+N+1, INF);
    fill(d2, d2+N+1, INF);
    d[s] = 0;
    que.push(P(0, s));
    while(!que.empty())
    {
        P p = que.top();    que.pop();
        int v = p.second;
        if(d2[v]<p.first)    continue;
        for(int i=0; i<Gra[v].size(); ++i)
        {
            edge &e = Gra[v][i];
            int dt2 = p.first + e.cost;
            if(d[e.to]>dt2)
            {
                swap(d[e.to],dt2);
                que.push(P(d[e.to],e.to));
            }
            if(d2[e.to]>dt2&&d[e.to]<dt2)
            {
                d2[e.to] = dt2;
                que.push(P(d2[e.to], e.to));
            }
        }
    }

}
int main()
{

    cin>>N>>R;
    for(int i=0;i<R;++i)
    {
        int f, to, cost;
        cin>>f>>to>>cost;
        Gra[f].push_back(edge(to,cost));
        Gra[to].push_back(edge(f,cost));
    }
    dijkstra(1);
    cout<<d2[N]<<endl;
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值