【Codeforces Alpha Round #20 C】Dijkstra?
阿新 • • 發佈:2020-12-08
題目連結
翻譯
讓你求出 \(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; }