codeforces 20C Dijkstra?

Description

You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.

Input

The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.

It is possible that the graph has loops and multiple edges between pair of vertices.

Output

Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.

Sample Input

Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
1 4 3 5 
题意:给出一张n个点m条边的无向图 (2 ≤ n ≤ 105, 0 ≤ m ≤ 105),输出从1到n的任意一条最短路径。
解法:dijkstra或者spfa,用pre数组记录到达每个点最短距离的前驱结点。
注意:
        路径的长度范围是 1 ≤ wi ≤ 106,从1到n的最短路径长度可能超出int范围。
        没有路径从1到达n时要输出-1。
#include 
#include 
#include 
#include 
using namespace std;
typedef long long LL;
typedef pair pii;
const int maxn = 100010;
const int maxm = 200010;
int v[maxm],next[maxm],w[maxm];
int first[maxn],pre[maxn],res[maxn],e;
LL d[maxn];

void init(){
    e = 0;
    memset(first,-1,sizeof(first));
}

void add_edge(int a,int b,int c){
    v[e] = b;next[e] = first[a];w[e] = c;first[a] = e++;
}

void dijkstra(int src){
    priority_queue ,greater > q;
    memset(d,-1,sizeof(d));
    d[src] = 0;
    q.push(make_pair(0,src));
    while(!q.empty()){
        while(!q.empty() && q.top().first > d[q.top().second])  q.pop();
        if(q.empty())   break;
        int u = q.top().second;
        q.pop();
        for(int i = first[u];i != -1;i = next[i]){
            if(d[v[i]] > d[u]+w[i] || d[v[i]] == -1){
                d[v[i]] = d[u]+w[i];
                q.push(make_pair(d[v[i]],v[i]));
                pre[v[i]] = u;
            }
        }
    }
}

int main(){
    init();
    int n,m,a,b,c;
    scanf("%d%d",&n,&m);
    for(int i = 0;i < m;i++){
        scanf("%d%d%d",&a,&b,&c);
        add_edge(a,b,c);
        add_edge(b,a,c);
    }
    dijkstra(1);
    int now = n,cnt = 0;
    if(d[n] == -1){
        printf("-1");
        return 0;
    }
    while(now != 1){
        res[cnt++] = now;
        now = pre[now];
    }
    res[cnt++] = 1;
    for(int i = cnt-1;i >= 0;i--)  printf("%d ",res[i]);
    return 0;
}

这题不错,正好最近在看最短路的东西,就拿它练手了~

你可能感兴趣的:(ACM题目,Dijkstra,最短路,SPFA)