Codeforces Alpha Round #20 (Codeforces format)
阿新 • • 發佈:2018-12-10
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
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
#include <bits/stdc++.h>
#define INF 0x3fffffff
#define mem(ar,num) memset(ar,num,sizeof(ar))
#define me(ar) memset(ar,0,sizeof(ar))
#define lowbit(x) (x&(-x))
#define IOS ios::sync_with_stdio(false)
#define DEBUG cout<<endl<<"DEBUG"<<endl;
using namespace std;
int n,m,head[100100],a,b,c,cnt,flag;
long long dis[100100];int vis[100100],po[100100],ans[100100];
struct no{
int next,to,w;
}edge[500100*2];
void add(int u,int v,int w){
edge[++cnt].next=head[u];
edge[cnt].to=v;
edge[cnt].w=w;
head[u]=cnt;
}
struct node{
int dis;
int pos;
bool operator <( const node &x )const{
return x.dis < dis;
}
};
bool dijkstra(){
priority_queue<node> q;
dis[1]=0;
ans[flag]=1;
q.push((node){0,1});
while(!q.empty()){
node tmp = q.top();
q.pop();
int x = tmp.pos, d = tmp.dis;
if(vis[x])
continue;
vis[x] = 1;
int t=head[x];
while(t){
int y=edge[t].to;
if(dis[y] > dis[x] + edge[t].w){
dis[y] = dis[x] + edge[t].w;
if(!vis[y]){
po[edge[t].to]=tmp.pos;//記錄路徑
q.push((node){dis[y],y});
}
}
t=edge[t].next;
}
}
if(dis[n]==0x7f7f7f7f7f7f7f7f)return false;
return true;
}
int main(){
mem(dis,0x7f);
cin>>n>>m;
for(int i=0;i<m;i++){
cin>>a>>b>>c;
add(a,b,c);
add(b,a,c);
}
if(dijkstra()){
for(int i=n;i;i=po[i]){
ans[++flag]=i;
}
for(int i=flag;i>=1;i--)
cout<<ans[i]<<" ";
}else cout<<-1<<endl;
return 0;
}