|
| 1 | +// https://atcoder.jp/contests/abc157/tasks/abc157_d |
| 2 | +// |
| 3 | +// 以下のクレートを使用。 |
| 4 | +// |
| 5 | +// - `itertools` |
| 6 | +// - `petgraph` |
| 7 | +// - `proconio` |
| 8 | + |
| 9 | +use itertools::Itertools as _; |
| 10 | +use petgraph::graphmap::UnGraphMap; |
| 11 | +use petgraph::unionfind::UnionFind; |
| 12 | +use proconio::input; |
| 13 | +use proconio::marker::Usize1; |
| 14 | + |
| 15 | +fn main() { |
| 16 | + // `proconio::input!`。 |
| 17 | + // |
| 18 | + // https://docs.rs/proconio/0.3.6/proconio/macro.input.html |
| 19 | + input! { |
| 20 | + n: usize, |
| 21 | + m: usize, |
| 22 | + k: usize, |
| 23 | + abs: [(Usize1, Usize1); m], |
| 24 | + cds: [(Usize1, Usize1); k], |
| 25 | + } |
| 26 | + |
| 27 | + // `petgraph::unionfind::UnionFind<_>`を使用。 |
| 28 | + // `UnionFind`は各集合のサイズは覚えてないので`vec![_; n]`で管理する。 |
| 29 | + // |
| 30 | + // https://docs.rs/petgraph/0.5/petgraph/unionfind/struct.UnionFind.html |
| 31 | + let mut ff = UnionFind::new(n); |
| 32 | + let mut ff_sizes = vec![1; n]; |
| 33 | + for &(a, b) in &abs { |
| 34 | + let size_sum = ff_sizes[ff.find(a)] + ff_sizes[ff.find(b)]; |
| 35 | + if ff.union(a, b) { |
| 36 | + ff_sizes[ff.find(a)] = size_sum; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + // `UnionFind`の`rank`はprivateな為面倒。ここではこのような方法で数える。 |
| 41 | + // この際`HashSet`のかわりに`petgraph::graphmap::GraphMap<..>`を使う。 |
| 42 | + // |
| 43 | + // https://docs.rs/petgraph/0.5/petgraph/graphmap/struct.GraphMap.html |
| 44 | + let mut ans = (0..n).map(|i| ff_sizes[ff.find(i)] - 1).collect::<Vec<_>>(); |
| 45 | + let mut already_decr = UnGraphMap::with_capacity(n, abs.len()); |
| 46 | + for (a, b) in abs { |
| 47 | + ans[a] -= 1; |
| 48 | + ans[b] -= 1; |
| 49 | + already_decr.add_edge(a, b, ()); |
| 50 | + } |
| 51 | + for (c, d) in cds { |
| 52 | + if ff.equiv(c, d) && !already_decr.contains_edge(c, d) { |
| 53 | + ans[c] -= 1; |
| 54 | + ans[d] -= 1; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + println!("{}", ans.iter().format(" ")); |
| 59 | +} |
0 commit comments