File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Authored by : scsc3204
2
+ // Co-authored by : BaaaaaaaaaaarkingDog
3
+ // http://boj.kr/ae6be2f242b44089a06fe25b5700ac0b
4
+ #include < bits/stdc++.h>
5
+ using namespace std ;
6
+
7
+ const int MX = 100'000 ;
8
+
9
+ int n, m;
10
+ int cnt, p[MX + 2 ];
11
+
12
+ int find (int x) {
13
+ if (p[x] < 0 ) return x;
14
+ return p[x] = find (p[x]);
15
+ }
16
+
17
+ void try_merge (int u, int v) {
18
+ u = find (u); v = find (v);
19
+ if (u == v) { cnt++; return ; }
20
+ if (p[u] > p[v]) swap (u, v);
21
+ p[u] += p[v];
22
+ p[v] = u;
23
+ }
24
+
25
+ int main () {
26
+ ios::sync_with_stdio (0 );
27
+ cin.tie (0 );
28
+
29
+ cin >> n >> m;
30
+ fill (p, p+n+1 , -1 );
31
+ for (int i = 0 ; i < m; i++) {
32
+ int u, v; cin >> u >> v;
33
+ try_merge (u, v);
34
+ }
35
+
36
+ cout << n - m - 1 + 2 *cnt;
37
+ }
38
+ /*
39
+ 유니온 파인드를 활용한 별해입니다.
40
+
41
+ 간선을 입력 받으면서 merge를 시도합니다.
42
+ 두 정점의 부모가 동일하지 않다면 merge를 수행합니다.
43
+ 두 정점의 부모가 동일한 경우
44
+ 해당 간선은 불필요한 간선이므로
45
+ 자르
656A
연산 횟수인 cnt를 증가시킵니다.
46
+
47
+ 이 연산을 완료한 뒤에 남은 간선 수는 총 (m - cnt)개가 됩니다.
48
+ 여기서 간선을 연결해 (n - 1)개의 간선을 확보해야 트리가 구성됩니다.
49
+ 따라서 연결해야 하는 간선 수는 (n - 1) - (m - cnt)개가 됩니다.
50
+
51
+ 그러므로 간선을 잇고 자르는 총 연산 수는
52
+ (n - 1) - (m - cnt) + cnt = n - m - 1 + 2*cnt이며,
53
+ 이를 답으로 출력합니다.
54
+ */
You can’t perform that action at this time.
0 commit comments