\(Dijkstra\) 算法,记录最短路的路径。
保证 \(Dijkstra\) 没问题,锅在记录路径。
//NEW
中夹的内容是记录路径的代码。
#include <bits/stdc++.h>
using namespace std;
struct Edge
{
int v, w;
// v --> to, w --> value
friend bool operator<(const Edge &x, const Edge &y)
{
return x.w > y.w;
}
};
const int maxn = 1e5 + 5;
vector<Edge> e[maxn];
//NEW
stack<int> out;
int pre[maxn];
//NEW
priority_queue<Edge> q;
int dis[maxn], vis[maxn], n, m, s;
void dijkstra()
{
dis[s] = 0;
q.push({s, 0});
while (!q.empty())
{
Edge inp = q.top();
q.pop();
int p = inp.v;
int tot = e[p].size();
if (vis[p])
continue;
vis[p] = 1;
for (int j = 0; j < tot; j++)
{
int v = e[p][j].v;
if (dis[v] > dis[p] + e[p][j].w)
{
dis[v] = dis[p] + e[p][j].w;
if (!vis[v])
{
q.push(Edge{v, dis[v]});
//NEW
pre[v] = p;
//NEW
}
}
}
}
return;
}
int main()
{
cin >> n >> m;
s = 1;
for (int i = 1; i <= n; i++)
{
dis[i] = 2147483647;
//NEW
pre[i] = -1;
//NEW
}
for (int i = 1; i <= m; i++)
{
int x, y, w;
cin >> x >> y >> w;
Edge inp;
inp.v = y, inp.w = w;
e[x].push_back({y, w});
e[y].push_back({x, w});
}
dijkstra();
//NEW
for (int i = n; i != -1; i = pre[i])
{
out.push(i);
}
int flag = 0;
while (!out.empty())
{
cout << out.top() << ' ';
out.pop();
flag = 1;
}
if(flag == 0)
cout << -1 << ' ';
//NEW
return 0;
}
标签:int,inp,maxn,push,NEW,byd,dis
From: https://www.cnblogs.com/qianxiquq/p/18209495