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 .

输入格式

The first line contains two integers n n n and m m m ( 2<=n<=10^5,0<=m<=10^5 ), where n n n is the number of vertices and m m m is the number of edges. Following m m m lines contain one edge each in form ai bi​ and wi ( 1<=ai,bi<=n,1<=wi<=10^6 ), 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.

输出格式

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.

输入 #1

5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1

输出 #1

1 4 3 5 

输入 #2

5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1

输出 #2

1 4 3 5 

思路:

模板题,最重要的是学会STL。

#include<iostream>
#include<queue>
#include<cstring> 
using namespace std;
typedef long long ll;
const int N=1e5+10;
const ll INF=1ll<<62;
vector<int>e[N];//定义可变二维数组 只有N行 
vector<int>w[N];
bool v[N];
ll d[N];
int p[N];
int n,m,a,b,c;
struct node
{
	ll d;
	int u;
	bool operator<(const node&rhs) const
	{
		return d>rhs.d;
	}
};
void Dijkstra()
{
	priority_queue<node>q;//优先队列 初始化定义 
	for(int i=1;i<=n;i++)
		d[i]=INF;
	d[1]=0;
	memset(v,0,sizeof(v));
	node tn;
	tn.d =0,tn.u =1;
	q.push(tn);//入队 
	while(!q.empty())
	{
		node t=q.top();
		q.pop();
		int u=t.u ;
		if(v[u])
			continue;
		v[u]=true;
		for(int i=0;i<e[u].size();i++)//队列元素个数 
		{
			int v=e[u][i];
			if(d[v]>d[u]+w[u][i])
			{
				d[v]=d[u]+w[u][i];
				p[v]=u;
				tn.d =d[v],tn.u =v;
				q.push(tn);
			}
		}
	}
}
int main()
{
	while(scanf("%d %d",&n,&m)!=EOF)
	{
		for(int i=1;i<=n;i++)
			e[i].clear(),w[i].clear();//清除元素个数 
		for(int i=0;i<m;i++)
		{
			scanf("%d %d %d",&a,&b,&c);
			e[a].push_back(b);
			w[a].push_back(c);
			e[b].push_back(a);
			w[b].push_back(c);//在尾部加一个数据 
		}
		Dijkstra();
		if(d[n]==INF)
			printf("-1\n");
		else
		{
			e[1].clear();
			e[1].push_back(n);
			while(p[n]!=1)
			{
				n=p[n];
				e[1].push_back(n);
			}
			e[1].push_back(1);
			for(int i=e[1].size()-1;i>0;i--)
				printf("%d ",e[1][i]);
			printf("%d\n",e[1][0]);
		}
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TherAndI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值