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

Sample 1

InputcopyOutputcopy
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

InputcopyOutputcopy
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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值