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 1
Inputcopy | Outputcopy |
---|---|
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1 | 1 4 3 5 |
Sample 2
Inputcopy | Outputcopy |
---|---|
5 6 1 2 2 2 5 5 2 3 4 1 4 1 4 3 3 3 5 1 | 1 4 3 5 |
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=100005;
const int maxb=2e5+5;
typedef long long ll;
const long long INF=9e13;
int n,m;
int a,b,c;
int head[maxn],pre[maxn];
bool vis[maxn];
ll dis[maxn];
int cnt;
struct edge
{
int next;
int to;
int cost;
}e[maxb];
struct node
{
int dis;
int id;
node(){}
node(int dis,int id):dis(dis),id(id){ }
bool operator < (const node &a) const
{
return dis>a.dis;
}
};
void begin()
{
memset(vis,0,sizeof(vis));
memset(head,-1,sizeof(head));
memset(pre,0,sizeof(pre));
cnt=0;
}
void build(int u,int v,int w)
{
e[cnt].to=v;
e[cnt].cost=w;
e[cnt].next=head[u];
head[u]=cnt++;
}
void dij(int x,int n)
{
priority_queue<node> q;
for(int i=0;i<=n;i++) dis[i]=INF;
dis[x]=0;
q.push(node(0,x));
node p;
while(!q.empty())
{
p=q.top();
q.pop();
int u=p.id;
if(vis[u]) continue;
vis[u]=1;
for(int i=head[u];i!=-1;i=e[i].next)
{
int j=e[i].to;
if(!vis[j]&&dis[j]>dis[u]+e[i].cost)
{
dis[j]=dis[u]+e[i].cost;
pre[j]=u;
q.push(node(dis[j],j));
}
}
}
return ;
}
void find(int x)
{
if(x!=1)
find(pre[x]);
if(x!=1)
cout<<" ";
cout<<x;
}
int main()
{
scanf("%d %d",&n,&m);
begin();
while(m--)
{
scanf("%d %d %d",&a,&b,&c);
build(a,b,c);
build(b,a,c);
}
dij(1,n);
if(dis[n]!=INF)
find(n);
else printf("-1");
cout<<endl;
}