Disjoint_Set의 개념으로 길이 배열을 한가지 더 선언해주어서 절대 차이만큼만 

더해주면서 저장하면 되는 것이었다. 

find 와 init 과정에서 parent 배열과 길이를 저장할 배열을 따로 만들어주었다. 

find를 호출할때마다 해당 노드의 루트노드를 탐색하고 루트노드까지의 길이를 해당 인덱스의

길이 배열에 저장해주었다. 

(어렵게 생각하기보단 풀리지 않는다면 Disjoint_set의 과정을 완벽히 이해해보시길 바랍니다.)

그래도 이해가 가지않는다면 댓글과 쪽지를 주세요!

스티커 이미지

<CODE>


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
//pda_pro12
#include<iostream>
#include<algorithm>
 
#define sz(x) x.size()
#define all(x) x.begin(), x.end()
#define N_ 20001
#define mod (int)1e3
 
using namespace std;
 
typedef long long ll;
typedef pair<intint> pll;
typedef double db;
 
int n, m, t, par[N_], len[N_];
 
void init() {
    for (int i = 1; i <= n; i++)
        par[i] = i, len[i] = 0;
    return;
}
 
int find(int x) {
    if (x == par[x])
        return x;
    else {
        int tmp = find(par[x]); 
        len[x] += len[par[x]]; 
        par[x] = tmp; 
        return tmp;
    }
}
 
void Merge(int x, int y) {
    len[x] = abs(x - y) % mod; 
    par[x] = y; 
}
 
int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> t;
    while (t--) {
        cin >> n;
        init(); 
        char inp; int a, b;
        while (1) {
            cin >> inp;
            if (inp == 'O')
                break
            else if (inp == 'E') {
                cin >> a;
                find(a); 
                cout << len[a] << '\n';
            }
            else if (inp == 'I') {
                cin >> a >> b;
                Merge(a, b);
            }
        }
    }
    return 0;
}


'PS) BOJ > Disjoint_set' 카테고리의 다른 글

[C++]미로 만들기 [BOJ 2665]  (0) 2018.08.21
[C++] 공항 [BOJ 10775]  (0) 2018.08.17

+ Recent posts