#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 1e5 + 10;
const LL INF = 1LL<<62;
vector<int> e[MAXN];//点
vector<int> w[MAXN];//权
bool vis[MAXN];
LL dis[MAXN];//距离
int prev[MAXN];//记录路径
int n,m;//点数和边数
struct node
{
LL d;//储存距离
int u;//点的标号
bool operator<(const node & rhs) const
{
return d>rhs.d;//距离短的优先
}
};
void dij()
{
priority_queue<node> q;//优先队列
for(int i=1;i<=n;i++)
{
dis[i]=INF;//距离初始化
}
dis[1]=0;//出发点的距离设置为1
memset(vis,0,sizeof(vis));//初始化
node tn;
tn.d=0;//出发点的距离为0
tn.u=1;//出发点为1
q.push(tn);//入队列
while(!q.empty())//队列为空说明已经遍历完了地图
{
node t=q.top();//出队列(最短的出)
q.pop();
int u=t.u;
if(vis[u]) continue;//判断是否访问过
vis[u]=true;//访问后标记
for(int i=0;i<e[u].size();i++)
{
int v = e[u][i];
if(dis[v]>dis[u]+w[u][i])
{
dis[v]=dis[u]+w[u][i];//择优选择
prev[v]=u;//记录路径
tn.d=dis[v];//记录距离
tn.u=v;//设置跳板
q.push(tn);//跳板入队列
}
}
}
}
//vector<int> getpath(int t)//路径还原
//{
// vector<int> path;
// for(;t!=-1;t=prev[t])
// {
// path.push_back(t);
// }
// reverse(path.begin(),path.end());
// return path;
// }
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
e[i].clear();
w[i].clear();
}
int a,b,c;
for(int i=1;i<=m;i++)
{
cin>>a>>b>>c;
e[a].push_back(b);
w[a].push_back(c);
e[b].push_back(a);
w[b].push_back(c);
}
dij();
if(dis[n]==INF) cout<<"-1"<<endl;
else
{
e[1].clear();
e[1].push_back(n);
while(prev[n]!=1)
{
n=prev[n];
e[1].push_back(n);
}
e[1].push_back(1);
for(int i=e[1].size()-1;i>0;i--)
{
cout<<e[1][i]<<" ";
}
cout<<e[1][0]<<endl;
}
return 0;
}
【codeforces 20C】 Dijkstra?(堆优化)最短路
最新推荐文章于 2020-09-12 22:07:21 发布