結果
問題 |
No.160 最短経路のうち辞書順最小
|
ユーザー |
|
提出日時 | 2025-09-02 12:11:28 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 8 ms / 5,000 ms |
コード長 | 2,234 bytes |
コンパイル時間 | 2,380 ms |
コンパイル使用メモリ | 213,548 KB |
実行使用メモリ | 7,716 KB |
最終ジャッジ日時 | 2025-09-02 12:11:33 |
合計ジャッジ時間 | 4,082 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 26 |
ソースコード
#include <bits/stdc++.h> using namespace std; vector<long long> dijkstra(vector<vector<pair<int,long long>>> &Graph,int start){ int N = Graph.size(); //O((V+E)logV) 一般最短経路魔法. long long inf = 3e18; vector<bool> used(N); vector<long long> ret(N,inf); priority_queue<pair<long long,int>,vector<pair<long long,int>>,greater<pair<long long,int>>> Q; ret.at(start) = 0; Q.push({0,start}); while(Q.size()){ auto[nowd,pos] = Q.top(); Q.pop(); if(used.at(pos)) continue; used.at(pos) = true; for(auto [to,w] : Graph.at(pos)){ if(ret.at(to) > nowd+w){ ret.at(to) = nowd+w; Q.push({ret.at(to),to}); } } } return ret; } vector<long long> dijkstra2(vector<vector<pair<int,long long>>> &Graph,int start){ int N = Graph.size(); //O(V^2) 密グラフ専用. long long inf = 3e18; vector<bool> used(N); vector<long long> ret(N,inf); ret.at(start) = 0; while(true){ long long nowd = inf,pos = -1; for(int i=0; i<N; i++){ if(used.at(i)) continue; if(nowd > ret.at(i)) nowd = ret.at(i),pos = i; } if(pos == -1) break; used.at(pos) = true; for(auto [to,w] : Graph.at(pos)){if(ret.at(to) > nowd+w) ret.at(to) = nowd+w;} } return ret; } int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int N,M,S,G; cin >> N >> M >> S >> G; vector<vector<pair<int,long long>>> Graph(N); for(int i=0; i<M; i++){ int u,v; cin >> u >> v; long long w; cin >> w; Graph.at(u).push_back({v,w}); Graph.at(v).push_back({u,w}); } auto dist1 = dijkstra2(Graph,S),distN = dijkstra2(Graph,G); auto dfs = [&](auto dfs,int pos,int back) -> void { if(pos == G){cout << pos << endl; return;} cout << pos << " "; sort(Graph.at(pos).begin(),Graph.at(pos).end()); for(auto [to,w] : Graph.at(pos)) if(to != back){ if(dist1.at(to)+distN.at(to) == dist1.at(pos)+distN.at(pos) && dist1.at(to) == dist1.at(pos)+w){ dfs(dfs,to,pos); return; } } }; dfs(dfs,S,-1); }