結果
| 問題 |
No.160 最短経路のうち辞書順最小
|
| コンテスト | |
| ユーザー |
utahta
|
| 提出日時 | 2020-04-10 23:15:41 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 15 ms / 5,000 ms |
| コード長 | 2,192 bytes |
| コンパイル時間 | 1,934 ms |
| コンパイル使用メモリ | 181,732 KB |
| 実行使用メモリ | 5,376 KB |
| 最終ジャッジ日時 | 2024-09-16 00:19:04 |
| 合計ジャッジ時間 | 3,127 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
#define each(i, c) for (auto& i : c)
#define mkp(a, b) make_pair(a, b)
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> Pll;
const ll MOD = 1e9+7;
template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << ": " << p.second << ")"; return os; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ", "; os << ")"; return os; }
template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; each (i, m) os << i << ", "; os << "}"; return os; }
typedef struct edge {
ll to;
ll cost;
} edge;
typedef vector<vector<edge>> G; // graph
typedef vector<Pll> GR; // graph result (cost, vertex num)
GR dijkstra(G &g, ll s) { // O(ElogV)
priority_queue<Pll, vector<Pll>, greater<Pll>> q;
GR res(g.size(), mkp(1e18, 0));
res[s] = mkp(0, s);
q.push(res[s]);
while (!q.empty()) {
auto p = q.top();
q.pop();
ll cost = p.first;
ll pos = p.second;
if (res[pos].first < cost) continue;
each (j, g[pos]) {
ll to = j.to;
ll to_cost = j.cost + cost;
if (to_cost >= res[to].first) continue;
res[to].first = to_cost;
q.push(mkp(to_cost, to));
}
}
return res;
}
vector<ll> dijkstra_restore_path(G &g, GR &res, ll s, ll e) {
ll from = e;
vector<ll> path = {from};
while (from != s) {
ll to = 1e18;
each (i, g[from]) {
if (res[from].first == res[i.to].first + i.cost) {
to = min(to, i.to);
}
}
from = to;
path.push_back(from);
}
//reverse(path.begin(), path.end());
return path;
}
int main() {
ll n, m, s, g;
cin >> n >> m >> s >> g;
G graph(n);
for (ll i = 0; i < m; ++i) {
ll a, b, c;
cin >> a >> b >> c;
graph[a].push_back(edge{.to = b, .cost = c});
graph[b].push_back(edge{.to = a, .cost = c});
}
swap(s, g);
auto res = dijkstra(graph, s);
auto ans = dijkstra_restore_path(graph, res, s, g);
for (ll i = 0; i < ans.size(); ++i) {
cout << ans[i];
if (i == ans.size()-1) cout << endl;
else cout << " ";
}
return 0;
}
utahta