POJ-3255 Roadblocks

 
 

求次短路問題,方法相似於求單源最短路,不過本題是將單源最短路和次最短路一塊求解ios

 

到某一點次最短路(eg:u): 假設最短路爲s->v->u , 次短路爲 s->v->u' 或 s->v'->u 注:s->v' 表示s->v 的次短路 ,v->u' 表示v->u 的次短路spa

須要作的就是同步更新單源最短路和次最短路blog

若當前節點爲u,與u相鄰節點爲vci

一、若與u相鄰的節點v,經過u能夠最小化s到其的距離,則更新其最短路,並記下原來s到v的最短路,以備更新次短路同步

二、 a、 若s經過u到v的路徑長度大於s到v的最小路徑長度,可是小於s到v的次短路長度,則更新s到v的次短路徑it

   b、 如果原來的最短路小於次短路,更新次短路io

#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;
}
相關文章
相關標籤/搜索