/* Fri Oct 24 20:42:14 JST 2003 */ #include #include #include typedef struct _node_t { char name[21]; struct _node_t *parent; struct _node_t *child[1000]; int n_children; } node_t; int depth(char s[]) { int i, len; len = strlen(s); for (i = 0; i < len; i++) { if (s[i] != ' ') return i; } return -1; } int free_tree(node_t *p, node_t *root) { int i; for (i = 0; i < p->n_children; i++) { free_tree(p->child[i], root); } if (p != root) { free(p); } } node_t *find(node_t *p, char name[]) { int i; node_t *q; if (strcmp(p->name, name) == 0) return p; for (i = 0; i < p->n_children; i++) { q = find(p->child[i], name); if (q != NULL) return q; } return NULL; } int child(node_t *p, char name[]) { if (p->parent == NULL) return 0; if (strcmp(p->parent->name, name) == 0) return 1; return 0; } int parent(node_t *p, char name[]) { int i; for (i = 0; i < p->n_children; i++) { if (strcmp(p->child[i]->name, name) == 0) return 1; } return 0; } int sibling(node_t *p, char name[]) { if (p->parent == NULL) return 0; return parent(p->parent, name); } int descendant(node_t *p, char name[]) { if (strcmp(p->name, name) == 0) return 1; if (p->parent == NULL) return 0; return descendant(p->parent, name); } int ancestor(node_t *p, char name[]) { int i; if (strcmp(p->name, name) == 0) return 1; for (i = 0; i < p->n_children; i++) { if (ancestor(p->child[i], name)) return 1; } return 0; } int main() { int n, m, d; node_t root, *p, *q; char *t; int i, j; char s[1024]; int newd; char X[72], Y[72]; int first = 1; while (1) { gets(s); sscanf(s, "%d %d", &n, &m); if (n == 0 && m == 0) break; d = 0; p = &root; gets(root.name); root.parent = NULL; root.n_children = 0; for (i = 1; i < n; i++) { gets(s); newd = depth(s); if (newd <= d) { for (j = 0; j < d-newd+1; j++) { p = p->parent; } } q = p->child[ p->n_children ] = malloc(sizeof(node_t)); strcpy(q->name, &s[newd]); q->parent = p; q->n_children = 0; p->n_children++; p = q; d = newd; } for (i = 0; i < m; i++) { gets(s); t = strtok( s, " "); p = find(&root, t); if (p == NULL) { printf("False\n"); continue; } t = strtok(NULL, " "); /* is */ t = strtok(NULL, " "); /* a or an or the */ t = strtok(NULL, " "); strtok(NULL, " "); /* of */ if (strcmp(t, "child") == 0) { t = strtok(NULL, " ."); if (child(p, t)) printf("True\n"); else printf("False\n"); } if (strcmp(t, "parent") == 0) { t = strtok(NULL, " ."); if (parent(p, t)) printf("True\n"); else printf("False\n"); } if (strcmp(t, "sibling") == 0) { t = strtok(NULL, " ."); if (sibling(p, t)) printf("True\n"); else printf("False\n"); } if (strcmp(t, "descendant") == 0) { t = strtok(NULL, " ."); if (descendant(p, t)) printf("True\n"); else printf("False\n"); } if (strcmp(t, "ancestor") == 0) { t = strtok(NULL, " ."); if (ancestor(p, t)) printf("True\n"); else printf("False\n"); } } printf("\n"); free_tree(&root, &root); } return 0; }