본문 바로가기
Computer Science

공통 조상 찾기 트리

by OKOK 2018. 12. 7.

1. 벡터와

2. 큐를 사용함

3. 벡터<벡터> 를 사용하여 트리 구조를 나타냄


1. 높이를 찾고

2. 공통 조상을 찾고

3. 아래 들어 있는 서브트리의 개수를 셈 


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
97
#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()
{
    freopen("input.txt""r", stdin);
    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


댓글