結果
問題 | No.2563 色ごとのグループ |
ユーザー |
![]() |
提出日時 | 2023-11-27 16:29:10 |
言語 | Rust (1.83.0 + proconio) |
結果 |
AC
|
実行時間 | 169 ms / 2,000 ms |
コード長 | 2,887 bytes |
コンパイル時間 | 14,268 ms |
コンパイル使用メモリ | 378,640 KB |
実行使用メモリ | 30,436 KB |
最終ジャッジ日時 | 2024-09-26 16:35:04 |
合計ジャッジ時間 | 17,971 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 35 |
ソースコード
use std::vec;macro_rules! input {($($r:tt)*) => {let stdin = std::io::stdin();let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));let mut next = move || -> String{bytes.by_ref().map(|r|r.unwrap() as char).skip_while(|c|c.is_whitespace()).take_while(|c|!c.is_whitespace()).collect()};input_inner!{next, $($r)*}};}macro_rules! input_inner {($next:expr) => {};($next:expr,) => {};($next:expr, $var:ident : $t:tt $($r:tt)*) => {let $var = read_value!($next, $t);input_inner!{$next $($r)*}};}macro_rules! read_value {($next:expr, ( $($t:tt),* )) => { ($(read_value!($next, $t)),*) };($next:expr, [ $t:tt ; $len:expr ]) => {(0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()};($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));}struct UnionFind {par: Vec<usize>,rank: Vec<usize>,}impl UnionFind {fn new(n: usize) -> Self {UnionFind {par: (0..n).collect(),rank: vec![0; n],}}fn root(&mut self, x: usize) -> usize {if self.par[x] == x {x} else {let par = self.par[x];let root = self.root(par);self.par[x] = root;root}}fn same(&mut self, x: usize, y: usize) -> bool {self.root(x) == self.root(y)}fn unite(&mut self, x: usize, y: usize) {let x = self.root(x);let y = self.root(y);if x == y {return;}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;}}}}fn main() {input! {n: usize,m: usize,c: [usize; n],edges: [(usize, usize); m],}let graph = {let mut graph = vec![vec![]; n];for (a, b) in edges {graph[a - 1].push(b - 1);graph[b - 1].push(a - 1);}graph};let colors = {let mut colors = vec![vec![]; n + 1];for i in 0..n {colors[c[i]].push(i);}colors};let mut uf = UnionFind::new(n);for i in 0..n {for &e in &graph[i] {if c[i] == c[e] {uf.unite(i, e);}}}let mut ans = 0;for color in colors {if color.len() == 0 {continue;}let re = color[0];for &i in &color {if !uf.same(re, i) {ans += 1;uf.unite(re, i);}}}println!("{}", ans);}