可以用这篇文章中2013年网研上机题目Problem D.文件系统基本一样的代码来做这道题,不过可以牺牲点空间,让程序更快,写起来也更简单点,代码如下:
#include<stdio.h>
#include<string.h>
struct Node {
int PID;
int child[101];
}tree[101];
void preRootOrder(int root) {
tree[root].PID = -1;
for(int i = 1;i <= 100;i++) {
if(tree[root].child[i] != -1) {
preRootOrder(i);
}
}
}
int main() {
int T;
scanf("%d",&T);
while(T--) {
memset(tree,-1,sizeof(tree));
tree[0].PID = 0;
int N;
scanf("%d",&N);
char s[6];
int a,b;
for(int i = 1;i <= N;i++) {
scanf("%s",s);
if(!strcmp(s,"FORK")) {
scanf("%d%d",&a,&b);
tree[a].child[b] = 1;
tree[b].PID = b;
} else {
if(!strcmp(s,"QUERY")) {
scanf("%d",&a);
if(tree[a].PID != -1) {
printf("Yes\n");
} else {
printf("No\n");
}
} else {
scanf("%d",&a);
if(tree[a].PID == -1 || a <= 0 || a > 100) {
continue;
}
preRootOrder(a);
}
}
}
}
}