-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathW6_P4.cpp
131 lines (124 loc) · 2.5 KB
/
W6_P4.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int data;
Node* par;
vector<Node*> chi_v;
Node(int data) {
this->data = data;
this->par = NULL;
}
};
class Tree {
public:
Node* root;
vector<Node*> node_v; //모든 노드를 저장할 벡터
Tree(int data) { //트리
Node* node = new Node(data);
this->root = node;
this->node_v.push_back(node);
}
void insertNode(int par_data, int data) {
Node* node = new Node(data);
for (int i = 0; i < node_v.size(); i++) {
if (node_v[i]->data == par_data) {
node_v[i]->chi_v.push_back(node);
node_v.push_back(node);
node->par = node_v[i];
return;
}
}
cout << -1 << endl; // 해당 부모노드가 없으면 -1출력
}
void delNode(int data) {
Node* curNode;
Node* parNode;
for (int i = 0; i < node_v.size(); i++) {
if (node_v[i]->data == data) {
if (node_v[i] == root) {
cout << -1 << endl;
return;
}
curNode = node_v[i];
parNode = curNode->par;
for (Node* child : curNode->chi_v) {
parNode->chi_v.push_back(child);
child->par = parNode;
}
for (int j = 0; j < parNode->chi_v.size(); j++) {
if (parNode->chi_v[j]->data == data) {
parNode->chi_v.erase(parNode->chi_v.begin() + j);
}
}
node_v.erase(node_v.begin() + i);
delete curNode;
return;
}
}
cout << -1 << endl;
}
void printChi(int data) {
for (int i = 0; i < node_v.size(); i++) {
if (node_v[i]->data == data) {
if (node_v[i]->chi_v.empty()) {
cout << -1 << endl;
return;
}
for (Node* child : node_v[i]->chi_v) {
cout << child->data << " ";
}
cout << endl;
return;
}
}
cout << -1 << endl;
}
void printPar(int data) {
for (int i = 0; i < node_v.size(); i++) {
if (node_v[i]->data == data) {
if (node_v[i] == root) {
cout << -1 << endl;
return;
}
cout << node_v[i]->par->data << endl;
return;
}
}
cout << -1 << endl;
}
void printLevel(int data) {
for (int i = 0; i < node_v.size(); i++) {
if (node_v[i]->data == data) {
/*if (node_v[i] == root) {
cout << 1 << endl;
return;
}*/
Node* curNode = node_v[i];
int lev = 1;
while (curNode!= root) {
curNode = curNode->par;
lev++;
}
cout << lev << endl;
return;
}
}
cout << -1 << endl;
}
};
int main() {
int n, t;
Tree tree(1);
cin >> n >> t;
int p, d;
for (int i = 0; i < n; i++) {
cin >> p >> d;
tree.insertNode(p, d);
}
for (int i = 0; i < t; i++) {
cin >> d;
tree.printLevel(d);
}
}