题目链接
翻译
让你求出 (1) 到 (n) 的最短路,打印路径。
题解
最短路堆优化。
记得 (dis) 数组开 (long long), 不然溢出会导致 (TLE) 问题 >_<
代码 (1) 是 (multiset) 写法。
代码 (2) 是 (priority queue) 写法。
代码1
#include <bits/stdc++.h>
#define LL long long
using namespace std;
struct abc{
int id;
LL dis;
bool operator<(const abc &b)const{
if (dis < b.dis){
return true;
}else if (dis == b.dis && id < b.id){
return true;
}
return false;
}
};
const int N = 1e5;
LL dis[N+10];
int n,m,pre[N + 10];
vector<pair<int,int> > g[N+10];
bool vis[N + 10];
multiset<abc> myset;
void dfs(int n){
if (n == 0){
return;
}
dfs(pre[n]);
cout << n <<" ";
}
int main(){
ios::sync_with_stdio(0),cin.tie(0);
cin >> n >> m;
for (int i = 1;i <= m; i++){
int x,y,z;
cin >> x >> y >> z;
g[x].push_back(make_pair(y,z));
g[y].push_back(make_pair(x,z));
}
memset(dis,255,sizeof dis);
dis[1] = 0;
abc temp;
temp.dis = 0;temp.id = 1;
myset.insert(temp);
while (!myset.empty()){
abc tmp = *(myset.begin());
myset.erase(myset.begin());
int x = tmp.id;
for (pair<LL,int> temp:g[x]){
int y = temp.first,w = temp.second;
if (dis[y] == -1 || dis[y] > dis[x] + w){
abc tmp;
if (dis[y] != -1){
tmp.dis = dis[y];tmp.id = y;
myset.erase(myset.find(tmp));
}
dis[y] = dis[x] + w;
pre[y] = x;
tmp.id = y;tmp.dis = dis[y];
myset.insert(tmp);
}
}
}
if (dis[n] == -1){
cout << -1 << endl;
}else{
dfs(n);
}
return 0;
}
代码2
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int N = 1e5;
LL dis[N+10];
int n,m,pre[N + 10];
vector<pair<int,int> > g[N+10];
priority_queue<pair<LL,int>,vector<pair<LL,int> >,greater<pair<LL,int> > > pq;
void dfs(int n){
if (n == 0){
return;
}
dfs(pre[n]);
cout << n <<" ";
}
int main(){
ios::sync_with_stdio(0),cin.tie(0);
cin >> n >> m;
for (int i = 1;i <= m; i++){
int x,y,z;
cin >> x >> y >> z;
g[x].push_back(make_pair(y,z));
g[y].push_back(make_pair(x,z));
}
memset(dis,255,sizeof dis);
dis[1] = 0;
pq.push(make_pair(0,1));
while (!pq.empty()){
pair<LL,int> tmp = pq.top();
pq.pop();
int x = tmp.second;
if (dis[x]!= -1 && dis[x] < tmp.first){
continue;
}
for (pair<LL,int> temp:g[x]){
int y = temp.first,w = temp.second;
if (dis[y] == -1 || dis[y] > dis[x] + w){
dis[y] = dis[x] + w;
pre[y] = x;
pq.push(make_pair(dis[y],y));
}
}
}
if (dis[n] == -1){
cout << -1 << endl;
}else{
dfs(n);
}
return 0;
}