以dijkstra为例,只需要一个path数组记录每一个点的前驱点,然后把这个数组摁到栈里再输出即可
当然,如果需要对每个点都求一遍,只需要在压栈之前加一个for循环
#include<pch.h>
#include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
#include <map>
#include <algorithm>
#include <stack>
#include <iomanip>
#include <cstring>
#include <cmath>
#define DETERMINATION main
#define lldin(a) scanf_s("%lld", &a)
#define println(a) printf("%lld\n", a)
#define reset(a, b) memset(a, b, sizeof(a))
const int INF = 0x3f3f3f3f;
using namespace std;
const double PI = acos(-1);
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const int mod = 1000000007;
const int tool_const = 19991126;
const int tool_const2 = 2000;
inline ll lldcin()
{
ll tmp = 0, si = 1;
char c;
c = getchar();
while (c > '9' || c < '0')
{
if (c == '-')
si = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
{
tmp = tmp * 10 + c - '0';
c = getchar();
}
return si * tmp;
}
///Untersee Boot IXD2(1942)
/**Although there will be many obstructs ahead,
the desire for victory still fills you with determination..**/
/**Last Remote**/
struct node
{
int next, toward, value;
}nodes[150000];
struct tmp
{
int number, distance;
};
int cnt = 0;
int heads[150000], distances[15000];
ll paths[150000];
void construction(int from, int to, int value)
{
nodes[cnt].value = value;
nodes[cnt].toward = to;
nodes[cnt].next = heads[from];
heads[from] = cnt++;
}
bool operator<(tmp a, tmp b)
{
return a.distance > b.distance;
}
void improved_dijkstra(int beginning)
{
reset(distances, 0x3f);
distances[beginning] = 0;
priority_queue<tmp>pq;
pq.push(tmp{ beginning,0 });
while (!pq.empty())
{
tmp current = pq.top();
pq.pop();
if (distances[current.number] != current.distance)
continue;
//cout<<current.number<<endl;
for (int i = heads[current.number]; i != -1; i = nodes[i].next)
{
int t = nodes[i].toward;
if (distances[t] > distances[current.number] + nodes[i].value)
{
distances[t] = distances[current.number] + nodes[i].value;
paths[t] = current.number;//记录前驱点
pq.push(tmp{ t,distances[t] });
}
}
}
}
int crossing, road;
void output(ll s, ll n)
{
ll pt = 1;
stack<ll>stk;
pt = n;
while (paths[pt] != -1)//塞入栈中直到不存在前驱点
{
stk.push(pt);
pt = paths[pt];
}
stk.push(pt);
while (stk.size())
{
cout << stk.top() << " ";
stk.pop();
}
cout << endl;
}
int DETERMINATION()
{
while (cin >> crossing >> road && crossing + road)
{
reset(heads, -1);
reset(paths, -1);
cnt = 0;
int tmp1, tmp2, tmp3;
for (int i = 1; i <= road; i++)
{
cin >> tmp1 >> tmp2 >> tmp3;
construction(tmp1, tmp2, tmp3);
construction(tmp2, tmp1, tmp3);
}
improved_dijkstra(1);
output(1, crossing);
cout << distances[crossing] << endl;
}
return 0;
}