[BOJ] 17398 통신망 분할

Time Lapse :NONE

17398.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <list>
#include <map>
#include <unordered_map>
#include <vector>
#include <stack>
#include <unordered_set>

using namespace std;

int n, m, q;
vector<pair<int, int>> edge;
vector<int> group;
vector<int> cnt;
stack<int> st;
unordered_set<int> s;
int n1, n2;
long res(0L);

int find(int n) {
return group[n] == n ? n : group[n] = find(group[n]);
}

void merge(int a, int b) {
int pa = find(a);
int pb = find(b);

if(pa != pb) {
group[pa] = pb;
cnt[pb] += cnt[pa];
}
}

int main() {
scanf("%d%d%d",&n,&m,&q);
edge.reserve(m + 1);
group = vector<int>(n + 1, 0);
cnt = vector<int>(n + 1, 1);
edge.push_back({0, 0});
for(int i = 1; i <= n; i++) group[i] = i;
for(int i = 1; i <= m; i++) {
scanf("%d%d",&n1,&n2);
edge.push_back({n1, n2});
s.insert(i);
}

for(int i = 0; i < q; i++) {
scanf("%d",&n1);
st.push(n1);
s.erase(n1);
}

for(auto num : s) {
merge(edge[num].first, edge[num].second);
}

while(!st.empty()) {
auto p = st.top(); st.pop();

int pa = find(edge[p].first);
int pb = find(edge[p].second);

if(pa == pb) continue;
res += (1L * cnt[pa] * cnt[pb]);
merge(pa, pb);
}

cout<<res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/08/04/PS/BOJ/17398/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.