結果
| 問題 |
No.556 仁義なきサルたち
|
| コンテスト | |
| ユーザー |
lzy9
|
| 提出日時 | 2018-04-01 14:52:16 |
| 言語 | Rust (1.83.0 + proconio) |
| 結果 |
AC
|
| 実行時間 | 15 ms / 2,000 ms |
| コード長 | 2,133 bytes |
| コンパイル時間 | 28,471 ms |
| コンパイル使用メモリ | 378,464 KB |
| 実行使用メモリ | 5,376 KB |
| 最終ジャッジ日時 | 2024-06-26 04:57:04 |
| 合計ジャッジ時間 | 18,496 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 22 |
コンパイルメッセージ
warning: field `rank` is never read
--> src/main.rs:37:5
|
35 | struct UnionFind {
| --------- field in this struct
36 | par: Vec<usize>,
37 | rank: Vec<usize>,
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: method `same` is never used
--> src/main.rs:52:8
|
42 | impl UnionFind {
| -------------- method in this implementation
...
52 | fn same(&mut self, a: usize, b: usize) -> bool {
| ^^^^
ソースコード
use std::io::*;
use std::str::FromStr;
use std::cmp::{min, max};
fn read<T: FromStr>() -> T {
let stdin = stdin();
let stdin_lock = stdin.lock();
let s = stdin_lock
.bytes()
.map(|c| c.unwrap() as char)
.skip_while(|c| c.is_whitespace())
.take_while(|c| !c.is_whitespace())
.collect::<String>();
s.parse::<T>().ok().unwrap()
}
fn main() {
let n: usize = read();
let m: usize = read();
let mut uf = UnionFind::new(n);
for _ in 0..m {
let a: usize = read::<usize>() - 1;
let b: usize = read::<usize>() - 1;
uf.union(a, b);
}
for i in 0..n {
println!("{}", uf.root(i) + 1);
}
}
struct UnionFind {
par: Vec<usize>,
rank: Vec<usize>,
groups: usize,
cnt: Vec<usize>,
}
impl UnionFind {
fn new(n: usize) -> UnionFind {
UnionFind {
par: (0..n).map(|i| i).collect(),
rank: vec![0; n],
groups: n,
cnt: vec![1; n],
}
}
fn same(&mut self, a: usize, b: usize) -> bool {
self.root(a) == self.root(b)
}
fn root(&mut self, a: usize) -> usize {
if self.par[a] == a {
a
} else {
let par = self.par[a];
self.par[a] = self.root(par);
self.par[a]
}
}
fn union(&mut self, a: usize, b: usize) {
let x = self.root(a);
let y = self.root(b);
if x == y {
return;
}
self.groups -= 1;
if self.cnt[x] < self.cnt[y] {
self.par[x] = y;
self.cnt[y] += self.cnt[x];
} else if self.cnt[x] == self.cnt[y] {
self.par[max(x, y)] = self.par[min(x, y)];
self.cnt[min(x, y)] += self.cnt[max(x, y)];
} else {
self.par[y] = x;
self.cnt[x] += self.cnt[y];
}
// if self.rank[x] < self.rank[y] {
// self.par[x] = y;
// } else {
// self.par[y] = x;
// if self.rank[x] == self.rank[y] {
// self.rank[x] += 1;
// }
// }
}
}
lzy9