poj 3255 次短路

Bessie搬到了一个新的农场,有时候他会回去看他的老朋友。但是他不想很快的回去,他喜欢欣赏沿途的风景,所以他会选择次短路,因为她知道一定有一条次短路。
这个乡村有R(1<=R<=100000)条双向道路,每一条连接N(1<=N<=5000)个点中的两个。Bessie在1号节点,他的朋友家是n号节点Input第一行:两个整数N和R
接下来R行:每行包含三个整数,A,B,D,表示一条连接A与B的长度为D的路径Output输出1到n的次短路Sample Input

4 4
1 2 100
2 4 200
2 3 250
3 4 100

Sample Output

450

Hint

Two routes: 1 -> 2 -> 4 (length 100+200=300) and 1 -> 2 -> 3 -> 4 (length 100+250+100=450)
代码
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define P pair<int,int>
const int N=1e5+10;
const int INF=2e9;
int n,r,dist[N],dist2[N];
struct Edge{
    int to,cost;
};
vector<Edge> G[N];
void addedge(int u,int v,int w)
{
    G[u].push_back(Edge{v,w});
    G[v].push_back(Edge{u,w});
}
void solve()
{
    priority_queue<P,vector<P>,greater<P> >q;
    fill(dist,dist+n,INF);
    fill(dist2,dist2+n,INF);
    dist[0]=0;
    q.push(P(0,0));
    while(!q.empty())
    {
        P p=q.top();q.pop();
        int v=p.second,d=p.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)
            {
                swap(dist[e.to],d2);
                q.push(P(dist[e.to],e.to));
            }
            if(dist2[e.to]>d2&&dist[e.to]<d2)
            {
                dist2[e.to]=d2;
                q.push(P(dist2[e.to],e.to));
            }            
         } 
    }
    printf("%d
",dist2[n-1]);
}
int main()
{
    scanf("%d%d",&n,&r);
    int u,v,w;
    for(int i=1;i<=r;i++)
    {
        scanf("%d%d%d",&u,&v,&w);
        u--,v--;
//        cout<<u<<" "<<v<<"
";
        addedge(u,v,w);
    }
    solve();
    return 0;
}
原文地址:https://www.cnblogs.com/hh13579/p/11363823.html