이 튜토리얼에서는 트리에서 조상-후손 관계에 대한 쿼리를 찾는 프로그램에 대해 논의할 것입니다.
이를 위해 루트 트리와 Q 쿼리가 제공됩니다. 우리의 임무는 쿼리에 주어진 두 루트가 다른 루트의 조상인지 아닌지를 찾는 것입니다.
예시
#include <bits/stdc++.h>
using namespace std;
//using DFS to find the relation between
//given nodes
void performingDFS(vector<int> g[], int u, int parent,
int timeIn[], int timeOut[], int& count) {
timeIn[u] = count++;
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (v != parent)
performingDFS(g, v, u, timeIn, timeOut, count);
}
//assigning out-time to a node
timeOut[u] = count++;
}
void processingEdges(int edges[][2], int V, int timeIn[], int timeOut[]) {
vector<int> g[V];
for (int i = 0; i < V - 1; i++) {
int u = edges[i][0];
int v = edges[i][1];
g[u].push_back(v);
g[v].push_back(u);
}
int count = 0;
performingDFS(g, 0, -1, timeIn, timeOut, count);
}
//checking if one is ancestor of another
string whetherAncestor(int u, int v, int timeIn[], int timeOut[]) {
bool b = (timeIn[u] <= timeIn[v] && timeOut[v] <= timeOut[u]);
return (b ? "yes" : "no");
}
int main() {
int edges[][2] = {
{ 0, 1 },
{ 0, 2 },
{ 1, 3 },
{ 1, 4 },
{ 2, 5 },
};
int E = sizeof(edges) / sizeof(edges[0]);
int V = E + 1;
int timeIn[V], timeOut[V];
processingEdges(edges, V, timeIn, timeOut);
int u = 1;
int v = 5;
cout << whetherAncestor(u, v, timeIn, timeOut) << endl;
return 0;
} 출력
no