본문 바로가기

알고리즘/SW EXPERT

1248. 공통 조상

1248. 공통 조상


공통 조상 같은 경우에는 LCA라고 하여, 해당하는 노드의 높이를 맞춰준 후에 같이 부모 노드로 거슬러 올라가면서 같은 노


드가 될 때까지 while 문을 이용하여 구할 수 있습니다. 


또한 문제에서 해당하는 조상 노드의 서브 트리의 크기를 구하라고 하였는데, 이는 분할정복을 이용하여 get_size() 함수에


서 자식 노드의 존재 여부를 파악하면서 재귀함수로 구현하였다. 처음에 get_size 에서 ret 값을 0으로 초기화 했었는데, 생각


보니 그렇게 하면 노드가 자기 자신도 서브 트리의 크기에 포함을 해야하므로 ret 의 초기값을 1로 수정하였다.


<정답 코드>


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
91
92
93
94
95
96
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
 
int get_depth(vector<int>& parent, int v)
{
    int ret = 0;
    int cur = v;
    while (cur != 1)
    {
        ret++;
        cur = parent[cur];
    }
 
    return ret;
}
 
int get_answer(vector<int>& parent, int n1, int n1_d, int n2, int n2_d)
{
    if (n1_d > n2_d)
    {
        while (n1_d != n2_d)
        {
            n1_d--;
            n1 = parent[n1];
        }
    }
 
    if (n1_d < n2_d)
    {
        while (n1_d != n2_d)
        {
            n2_d--;
            n2 = parent[n2];
        }
    }
 
    while (n1 != n2)
    {
        n1 = parent[n1];
        n2 = parent[n2];
    }
 
 
    return n1;
}
 
int get_size(vector<vector<int>>& child, int cur)
{
    int ret = 1;
 
    if (child[cur].size() == 0)
        return 1;
 
    for (int i = 0; i < child[cur].size(); i++)
    {
        ret += get_size(child, child[cur][i]);
    }
 
    return ret;
}
int main()
{
    int tc;
    cin >> tc;
 
    for (int t = 1; t <= tc; t++)
    {
        int V, E, node1, node2;
        int node1_depth, node2_depth;
        cin >> V >> E >> node1 >> node2;
 
        vector<int> parent(V + 1);
        vector<vector<int>> child(V + 1);
 
        for (int i = 0; i < E; i++)
        {
            int from, to;
            cin >> from >> to;
            parent[to] = from;
            child[from].push_back(to);
        }
 
        node1_depth = get_depth(parent, node1);
        node2_depth = get_depth(parent, node2);
 
        int ancess = get_answer(parent, node1, node1_depth, node2, node2_depth);
        int size = get_size(child, ancess);
 
        cout << "#" << t << " " << ancess << " " << size << endl;
 
    }
 
    return 0;
}
cs


반응형

'알고리즘 > SW EXPERT' 카테고리의 다른 글

1247.최적경로  (0) 2018.09.05
5213. 진수의 홀수 약수  (0) 2018.09.05
5170. 상원이의 직선 긋기 게임  (0) 2018.08.03
4676. 늘어지는 소리 만들기  (0) 2018.08.02
4698. 테네스의 특별한 소수  (0) 2018.07.30