给定一棵树,询问两个节点x和y,判断x是否是y的祖先
好吧,我承认对于带时间戳dfs我还不是那么了解,看了题解之后才有恍然大悟的感觉,这种写法我记下了
如果一个节点是另一个节点的祖先,那么我们遍历这棵树的时候,到达这个节点的时间肯定比另一个节点早,并且第二次到达这个节点的时候肯定比另一个节点晚,这就是时间戳的应用,那么我们只需要遍历一遍这棵树,O(n)的复杂度,预处理出来所有的节点两次访问的时间,然后询问的时候直接按照条件询问即可。
需掌握且必须掌握的就是时间戳dfs
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
const int maxn = 300010;
const int maxtot = 20000010;
int cs, n, c[maxn], start[maxn], pre[maxtot], post[maxtot], dfs_clock;
void dfs(int root){
stack<int> st;
st.push(root);
pre[root] = 0;
dfs_clock = 1;
while(!st.empty()){
int u = st.top();
if (pre[u]){
post[u] = dfs_clock++;
st.pop();
continue;
}
pre[u] = dfs_clock++;
for (int i = start[u]; i < start[u] + c[u]; i++){
if (i < n){
pre[i] = 0; st.push(i);
}
else{
pre[i] = dfs_clock++; post[i] = dfs_clock++;
}
}
}
}
int main(){
scanf("%d", &cs);
for (int k = 1; k <= cs; k++){
printf("Case %d:\n", k);
scanf("%d", &n);
int s = 1;
for (int i = 0; i < n; i++){
scanf("%d", &c[i]);
start[i] = s; s += c[i];
}
dfs(0);
int m, x, y;
scanf("%d", &m);
while(m--){
scanf("%d%d", &x, &y);
if (pre[x] < pre[y] && post[x] > post[y]) puts("Yes");
else puts("No");
}
if (k < cs) puts("");
}
return 0;
}