Codeforces Alpha Round #20 (Codeforces format) C. Dijkstra?

 题目

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 aibi 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.

Examples

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 

 代码

+ 本题题目中说会有重边, 以为要将每条边的边权更新成最小值,但其实不用

+ 最短路径可能会爆int

#include<iostream>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
#define _for(i,a,b) for(int i=(a);i<(b);i++)
#define _rep(i,a,b) for(int i=(a);i<=(b);i++)
typedef pair<int, int> PLL;
typedef long long ll;
const int N = 2e5+5;
const ll INF = 100000000005; // 不能使用int的 INF
int readint(){
    int x;scanf("%d",&x);return x;
}
struct Node {
    int v, w;
};
vector<Node> edge[N];
int n, m, k;
ll dist[N]; // 因为一条边的权值最多可达1e6, 最短路径长度可能会爆int
int pre[N * 2];
bool distOver[N];
void printPath(int s, int t) {
    if(pre[t] != s) {
        printPath(s, pre[t]);
    } else {
        printf("%d ", s);
    }
    printf("%d ", t);
    
}
void Djikstra(int s, int t) {
    _rep(i, 1, n) // 初始化dist数组
        dist[i] = INF;
    memset(distOver, false, sizeof(distOver));
    priority_queue<PLL, vector<PLL>, greater<PLL> > q;
    dist[s] = 0;
    q.push({dist[s], s});
    while(!q.empty()) {
        int x = q.top().second; q.pop();
        if(distOver[x]) continue;
        distOver[x] = true;
        for(auto y : edge[x]) {
            if(dist[x] + y.w < dist[y.v]) {
                dist[y.v] = dist[x] + y.w;
                pre[y.v] = x;
                q.push({dist[y.v], y.v});
            }
        }
    }
    if(dist[t] >= INF) {
        puts("-1");
        return;
    }
    printPath(s, t);
}
int main()
{
    n = readint(), m = readint();
    _rep(i, 1, m) {
        int x = readint(), y = readint(), w = readint(); 
        edge[x].push_back({y, w});
        edge[y].push_back({x, w}); 
    }
    Djikstra(1, n);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值