题目
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.
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;
}