在本教程中,我们将讨论在树中查找祖先与后代关系的查询程序。
为此,我们将提供有根的树和Q查询。我们的任务是查找查询中给定的两个根是否为另一个的祖先。
#include <bits/stdc++.h>
using namespace std;
//使用DFS查找
//给定节点
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);
}
//将超时分配给节点
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);
}
//检查一个人是否是另一个人的祖先
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