Skip to content

Commit 4711bcc

Browse files
committed
add abc399c.rs
1 parent 9f4e7f4 commit 4711bcc

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

src/abc/abc399c.rs

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/** THIS IS AN OUTPUT FILE. NOT EDIT THIS FILE DIRECTLY. **/
2+
use proconio::input;
3+
use proconio::marker::*;
4+
use std::marker::PhantomData;
5+
use std::cmp::*;
6+
use std::collections::*;
7+
8+
struct UnionFind {
9+
parents: Vec<usize>,
10+
sizes: Vec<usize>,
11+
ranks: Vec<usize>
12+
}
13+
14+
impl UnionFind {
15+
fn new(n:usize) -> UnionFind {
16+
let mut uf = UnionFind { parents: vec![0;n], sizes:vec![1;n], ranks:vec![0;n] };
17+
for i in 0..n {
18+
uf.parents[i] = i;
19+
}
20+
uf
21+
}
22+
23+
fn root(&mut self, x:usize) -> usize {
24+
let ti = self.parents[x];
25+
if ti == x {
26+
x
27+
} else {
28+
self.parents[x] = self.root(ti);
29+
self.parents[x]
30+
}
31+
}
32+
33+
fn is_same(&mut self, x:usize, y:usize) -> bool {
34+
self.root(x) == self.root(y)
35+
}
36+
37+
fn unite(&mut self, x:usize, y:usize) -> bool {
38+
let rx = self.root(x);
39+
let ry = self.root(y);
40+
if rx == ry { return false }
41+
let (rx, ry) = if self.ranks[rx] < self.ranks[ry] {
42+
(ry, rx)
43+
} else {
44+
(rx, ry)
45+
};
46+
self.parents[ry] = rx;
47+
if self.ranks[rx] == self.ranks[ry] {
48+
self.ranks[rx] += 1;
49+
}
50+
51+
self.sizes[rx] += self.sizes[ry];
52+
true
53+
}
54+
55+
fn group_size(&mut self, x:usize) -> usize {
56+
let i = self.root(x);
57+
self.sizes[i]
58+
}
59+
}
60+
61+
fn main() {
62+
input! {
63+
n:usize,
64+
m:usize,
65+
edges: [(Usize1, Usize1);m]
66+
}
67+
68+
let mut ut = UnionFind::new(n);
69+
70+
for &(a, b) in &edges {
71+
ut.unite(a, b);
72+
}
73+
74+
let mut map = HashMap::new();
75+
for &(a, _) in &edges {
76+
let pi = ut.root(a);
77+
*map.entry(pi).or_insert(0) += 1;
78+
}
79+
80+
let mut result = 0;
81+
for (i, num) in map {
82+
result += num - (ut.group_size(i) - 1);
83+
}
84+
85+
println!("{}", result);
86+
}

0 commit comments

Comments
 (0)