結果
| 問題 |
No.160 最短経路のうち辞書順最小
|
| コンテスト | |
| ユーザー |
lzy9
|
| 提出日時 | 2018-03-29 22:32:05 |
| 言語 | Rust (1.83.0 + proconio) |
| 結果 |
AC
|
| 実行時間 | 5 ms / 5,000 ms |
| コード長 | 2,092 bytes |
| コンパイル時間 | 15,197 ms |
| コンパイル使用メモリ | 383,516 KB |
| 実行使用メモリ | 6,944 KB |
| 最終ジャッジ日時 | 2024-06-26 00:03:52 |
| 合計ジャッジ時間 | 13,276 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
use std::io;
use std::cmp;
use std::cmp::Ordering;
use std::usize;
use std::collections::BinaryHeap;
fn main() {
solve();
}
fn solve() {
let mut str = String::new();
io::stdin().read_line(&mut str).unwrap();
let mut input: Vec<usize> = str.split_whitespace().map(|x| x.parse().unwrap()).collect();
let n = input[0];
let m = input[1];
let s = input[2];
let g = input[3];
let mut graph: Vec<Vec<Edge>> = (0..n).map(|_| Vec::new()).collect();
for _ in 0..m {
str = String::new();
io::stdin().read_line(&mut str).unwrap();
input = str.split_whitespace().map(|x| x.parse().unwrap()).collect();
graph[input[0]].push(Edge { to: input[1], cost: input[2] });
graph[input[1]].push(Edge { to: input[0], cost: input[2] });
}
let mut dist: Vec<_> = (0..n).map(|_| usize::MAX).collect();
let mut pre: Vec<_> = (0..n).map(|i| i).collect();
let mut heap = BinaryHeap::new();
heap.push(Node { id: g, cost: 0 });
dist[g] = 0;
while let Some(Node {id, cost}) = heap.pop() {
if dist[id] < cost {
continue;
}
for edge in &graph[id] {
if cost + edge.cost < dist[edge.to] {
heap.push(Node { id: edge.to, cost: cost + edge.cost });
dist[edge.to] = cost + edge.cost;
pre[edge.to] = id;
}
if cost + edge.cost == dist[edge.to] {
pre[edge.to] = cmp::min(pre[edge.to], id);
}
}
}
let mut current = s;
while current != g {
print!("{} ", current);
current = pre[current];
}
println!("{}", current);
}
struct Edge {
to: usize,
cost: usize,
}
#[derive(Copy, Clone, Eq, PartialEq)]
struct Node {
id: usize,
cost: usize,
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost).then_with(|| self.id.cmp(&other.id))
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Node) -> Option<Ordering> {
Some(self.cmp(other))
}
}
lzy9