POJ-3255 Roadblocks

求次短路问题,方法类似于求单源最短路,不过本题是将单源最短路和次最短路一块求解

 

到某一点次最短路(eg:u): 假设最短路为s->v->u , 次短路为 s->v->u' 或 s->v'->u 注:s->v' 表示s->v 的次短路 ,v->u' 表示v->u 的次短路

需要做的就是同步更新单源最短路和次最短路

若当前节点为u,与u相邻节点为v

1、若与u相邻的节点v,通过u可以最小化s到其的距离,则更新其最短路,并记下原来s到v的最短路,以备更新次短路

2、 a、 若s通过u到v的路径长度大于s到v的最小路径长度,但是小于s到v的次短路长度,则更新s到v的次短路径

   b、 若是原来的最短路小于次短路,更新次短路

#include <iostream>
#include <vector>
#include <queue>
#define maxn 100010
#define INF 9999999999
using namespace std;
typedef pair<int,int>p;
struct edge {
    int from;
    int to;
    long long  cost;
};

int n,r;
vector <edge> g[maxn];
long long dist[maxn],dist2[maxn];

void solve(){
    priority_queue<p,vector<p>,greater<p> > que;
    fill(dist,dist+n,INF);
    fill(dist2,dist2+n,INF);
    dist[0] = 0;
    que.push(p(0,0));

    while(!que.empty()){
        p pp = que.top();
        que.pop();
        int v = pp.second;
        int d = pp.first;
        if (dist2[v] < d )
            continue;
        for (int i=0;i<g[v].size();i++){
            edge &e = g[v][i];
            int d2 = d+ e.cost;
            if (dist[e.to] > d2){
                int tp = dist[e.to];
                dist[e.to] = d2;
                d2 = tp;
                que.push(p(dist[e.to],e.to));
            }
            if (dist2[e.to] > d2 && dist[e.to] <d2){
                dist2[e.to]=d2;
                que.push(p(dist2[e.to],e.to));
            }
        }
    }
    cout<< dist2[n-1]<<endl;
}

int main()
{
    cin>>n>>r;
    edge tmp,tmp1;
    int from,to,cost;
    for(int i=0;i<r;i++){
        cin>>from>>to>>cost;
        //cout<<tmp.from<<tmp.to<<tmp.cost;
        tmp.from = from -1;
        tmp.to = to-1;
        tmp.cost =cost;
        g[from-1].push_back(tmp);
        tmp1.from = to-1;
        tmp1.to = from -1;
        tmp1.cost = cost;
        g[to-1].push_back(tmp1);
    }
    solve();
    return 0;
}

  

转载于:https://www.cnblogs.com/Bang-cansee/p/5935621.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值