카테고리 없음
백준 연결요소의 갯수 11724
벤치마킹
2019. 6. 11. 01:38
Disjoint-Set / 문제로 쉽게 연결되는 고리와 어느 지점에서 그 부모를 찾을수 있는 자료구조를 연습
https://www.acmicpc.net/problem/11724
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | #include <stdio.h> #include <iostream> #include <memory.h> using namespace std; int parent[1000005]; int ans = 0; int arr[1000005] = { 0, }; // 부모를 찾아주는 함수 int find(int x){ int root = -1; if (parent[x] == x) root = x; else root = find(parent[x]); parent[x] = root; return root; } //b를 a와 연결시켜주는 함수 // void link(int a, int b) { //결국 여기서 .. 부모를 찾아 줌.. int pa = find(a); int pb = find(b); if (pa != pb) arr[pa] += arr[pb]; else return; parent[pb] = pa; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int N, M; int a, b; // freopen("input.txt", "r", stdin); setbuf(stdout, NULL); cin >> N >> M; for (int i = 1; i <= N; i++){ parent[i] = i; } for (int i = 0; i < M; i++){ cin >> a >> b; link(a, b); } ans = N; for (int i = 1; i <= N; i++){ //결국 1번부터 N 번까지 부모를 찾아서 i 와 같으면 --> 그경우는 부모와 본인이 같으므로 //연결 요소는 아님 즉 어디에 연관되어져있따. if (find(i) != i) ans--; } cout << ans << "\n"; return 0; } | cs |