A professor of anthropology was interested in people living in isolated islands and their history. He collected their family trees to conduct some anthropological experiment. For the experiment, he needed to process the family trees with a computer. For that purpose he translated them into text files. The following is an example of a text file representing a family tree.
John
Robert
Frank
Andrew
Nancy
David
Each line contains the given name of a person. The name in the first line is the oldest ancestor in this family tree. The family tree contains only the descendants of the oldest ancestor. Their husbands and wives are not shown in the family tree. The children of a person are indented with one more space than the parent. For example, Robert and Nancy are the children of John, and Frank and Andrew are the children of Robert. David is indented with one more space than Robert, but he is not a child of Robert, but of Nancy. To represent a family tree in this way, the professor excluded some people from the family trees so that no one had both parents in a family tree.
For the experiment, the professor also collected documents of the families and extracted the set of statements about relations of two persons in each family tree. The following are some examples of statements about the family above.
John is the parent of Robert.
Robert is a sibling of Nancy.
David is a descendant of Robert.
For the experiment, he needs to check whether each statement is true or not. For example, the first two statements above are true and the last statement is false. Since this task is tedious, he would like to check it by a computer program.
Input
The input contains several data sets. Each data set consists of a family tree and a set of statements. The first line of each data set contains two integers n (0 < n < 1000) and m (0 < m < 1000) which represent the number of names in the family tree and the number of statements, respectively. Each line of the input has less than 70 characters.
As a name, we consider any character string consisting of only alphabetic characters. The names in a family tree have less than 20 characters. The name in the first line of the family tree has no leading spaces. The other names in the family tree are indented with at least one space, i.e., they are descendants of the person in the first line. You can assume that if a name in the family tree is indented with k spaces, the name in the next line is indented with at most k + 1 spaces. This guarantees that each person except the oldest ancestor has his or her parent in the family tree. No name appears twice in the same family tree. Each line of the family tree contains no redundant spaces at the end.
Each statement occupies one line and is written in one of the following formats, where X and Y are different names in the family tree.
X is a child of Y.
X is the parent of Y.
X is a sibling of Y.
X is a descendant of Y.
X is an ancestor of Y.
Names not appearing in the family tree are never used in the statements. Consecutive words in a statement are separated by a single space. Each statement contains no redundant spaces at the beginning and at the end of the line.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
For each statement in a data set, your program should output one line containing True or False. The first letter of True or False in the output must be a capital. The output for each data set should be followed by an empty line.
Examples
Input
6 5
John
Robert
Frank
Andrew
Nancy
David
Robert is a child of John.
Robert is an ancestor of Andrew.
Robert is a sibling of Nancy.
Nancy is the parent of Frank.
John is a descendant of Andrew.
2 1
abc
xyz
xyz is a child of abc.
0 0
Output
True
True
True
False
False
True
Input
6 5
John
Robert
Frank
Andrew
Nancy
David
Robert is a child of John.
Robert is an ancestor of Andrew.
Robert is a sibling of Nancy.
Nancy is the parent of Frank.
John is a descendant of Andrew.
2 1
abc
xyz
xyz is a child of abc.
0 0
Output
True
True
True
False
False
True
We are given a problem about checking relationships in a family tree represented by indentation. The input contains multiple datasets. Each dataset has n and m, then n lines of names (with leading spaces indicating indentation), then m statements. We need to output True or False for each statement, with an empty line after each dataset.
We need to parse the family tree. The tree is defined by indentation: the number of leading spaces determines the depth. The root has depth 0 (no leading spaces). For each subsequent line, the depth is at most previous depth + 1. And each person (except root) has a parent: the most recent person with depth = current depth - 1 (the immediate previous line with one less indentation). Actually typical parsing: We maintain a stack of ancestors based on depth.
We'll store for each person: name, depth, parent (maybe pointer or name), children list, ancestors/descendants.
We need to answer relationships: child, parent, sibling, descendant, ancestor. Since names are unique, we can map name to node index.
Definitions:
X is a child of Y: Y is the parent of X. So we can check if parent(X) == Y.
X is the parent of Y: parent(Y) == X.
X is a sibling of Y: X != Y and parent(X) == parent(Y) (both defined, including root? Root has no parent, so root cannot be sibling with anyone because it has no parent; but statements guarantee X and Y are different names in tree. If one is root, then they cannot be siblings because they would not share parent. So we can just check if they have same parent and are not same.)
X is a descendant of Y: Y is an ancestor of X, i.e., X is in the subtree of Y. This includes child, grandchild, etc. We need to check if Y is an ancestor of X. So we can traverse up from X to root and see if Y appears.
X is an ancestor of Y: Y is descendant of X. So check if X is ancestor of Y.
Thus we need to be able to get parent quickly. We'll also need to compute ancestor/descendant. Since n <= 1000, we can precompute ancestor sets or just traverse upward for each query (max depth maybe up to n, but m also <=1000, so O(m * n) fine). But we could also compute parent pointers and then for each query climb.
But careful: The family tree representation may have missing parents? The problem says each person except oldest ancestor has his or her parent in the tree. So parent exists for all non-root.
Also note that indentation is measured by spaces. The number of spaces can be any? But they said each line contains less than 70 characters. The indent is at least one space for descendants. We need to count leading spaces. Since the lines could contain spaces only as indentation? Actually the name is alphabetic, but there could be leading spaces. The line may have spaces before the name. So we need to count number of leading spaces. But we need to be careful: Tabs? Probably only spaces. They said "Each line of the input has less than 70 characters." and "The name in the first line of the family tree has no leading spaces. The other names in the family tree are indented with at least one space, i.e., they are descendants of the person in the first line." So we can count spaces.
However there is a nuance: "You can assume that if a name in the family tree is indented with k spaces, the name in the next line is indented with at most k + 1 spaces." This ensures that the parent is the immediate previous line with depth k. But there could be situations where depth decreases? They didn't say it's always increasing; they only guarantee at most k+1. So depth can stay the same or increase by 1, or possibly decrease? Actually "at most k+1 spaces" means it could be less than k+1, i.e., could be same or less? The phrase "at most k + 1 spaces" means the next line's leading spaces is <= k+1. But we need to parse the tree correctly. Typically, in such problems, the tree is given in a pre-order traversal where indentation shows depth. When depth decreases, it indicates moving back up. So we can parse using a stack: For each line, compute its depth d (count spaces). Then pop from stack until stack size = d (or stack depth equals d). Because root depth=0. Actually depth is number of leading spaces? But if root has 0 spaces, then depth=0. Children have 1 space? They said "children of a person are indented with one more space than the parent." So the depth is number of leading spaces? But they said "if a name in the family tree is indented with k spaces, the name in the next line is indented with at most k + 1 spaces." So depth can only increase by 1 at most, but can stay same or decrease. How to interpret? Usually, the tree is represented in a "pretty print" indentation: Each child is indented by one more space than its parent. The children are listed in order. So if we have:
John (depth 0)
Robert (depth 1)
Frank (depth 2)
Andrew (depth 2)
Nancy (depth 1)
David (depth 2)
So we can compute depth = number of leading spaces. The parent of a node is the most recent node with depth = current depth - 1. That can be found by maintaining a stack of ancestors as we parse.
Algorithm: Initialize an empty stack. For each line (i from 0 to n-1):
Read the line as s (including leading spaces, but we may read using getline; careful: we cannot use simple cin >> because spaces are important; we need to read entire line). We'll count leading spaces: find first non-space character; the number of spaces before it is the depth. But note that the name itself may contain spaces? No, name is only alphabetic characters, so no spaces. So the line consists of leading spaces followed by the name, and no trailing spaces.
Let depth = number of leading spaces.
Create node: name = s.substr(first_non_space) (trim leading spaces). Actually we need to store the name string without spaces.
Now we need to determine its parent: The stack should contain nodes for the current ancestors. The root depth is 0. For depth d, the parent is the node at depth d-1. The stack's size (depth) indicates the depth of the last node? Actually if we push each node onto the stack, the stack represents the current path from root to the previous node. The depth of the node at stack position i is i (if root depth 0). For example, after reading John, stack = [John] (size 1, depth index 0). After reading Robert depth=1, we want parent = stack[0] (John). After reading Frank depth=2, parent = stack[1] (Robert). After reading Andrew depth=2, the stack currently is [John, Robert, Frank]? Actually after Frank, stack would be [John, Robert, Frank]. But Andrew depth=2, we need to pop until stack size = depth? Since depth=2, the stack should have size = depth (the number of ancestors currently at depth less than current). Specifically, for depth d, the parent should be the node at depth d-1, which is at index d-1 in the stack if stack size >= d. However, after Frank (depth 2), stack size = 3 (indices: 0->depth0,1->depth1,2->depth2). For Andrew, we need to set parent to node at depth 1 (Robert). But the stack's top is Frank (depth2). However, the stack currently contains Frank as the last node, which is at depth2, but we need to adjust the stack to reflect the path to the new node. In a pre-order traversal, when we go to a sibling, we go back to the parent's depth. Typically, we pop nodes until stack size == depth, then the parent is the node at depth-1 (which is the new top after popping? Actually after popping, the stack will have size = depth, representing ancestors up to depth-1). Then we push the new node.
So algorithm: For each line:
depth = count spaces.
while stack.size() > depth: pop().
Now stack size == depth. The new node's parent is stack.top() if depth > 0; otherwise it's root with no parent.
Add node: record parent, and add to children list of parent if any.
Push the node onto stack.
This works because the input is guaranteed to be valid such that the parent exists (the most recent node with depth-1 is at stack top after popping to correct depth). The guarantee that next line's depth <= previous depth+1 ensures that we won't need to pop more than necessary? Actually depth could be less than current stack size, so popping to match depth works. And if depth > current stack size? It could be at most previous depth+1, but previous depth was stack.size()-1? Actually after processing previous line, stack size = previous depth +1 (since root depth0 gives size1). So if current depth = previous depth+1, then stack.size() == previous depth+1 = depth, so while condition false, no pop. Then we push, making stack size depth+1. If current depth = previous depth, then stack.size() = previous depth+1 > depth, so we pop once? Actually if previous depth = d, stack size = d+1. For current depth = d, we pop until stack.size() == d, so one pop. That gives correct parent: after popping, stack size = d, top is node at depth d-1 (the parent of previous node), which is also the parent of the new node (since they are siblings). So parent = stack.top() (depth d-1). Good. If current depth < previous depth, we pop multiple times until stack.size() == depth. For example, after Frank depth2, stack size =3. Then Andrew depth2, we pop until size=2? Actually depth=2, we pop until size=2, but size is 3, pop once yields size2, top is Robert (depth1). That's correct. Then after Andrew, stack becomes [John, Robert, Andrew]? Actually we popped Frank, then push Andrew: stack [John, Robert, Andrew]. Then next line Nancy depth=1. For depth=1, pop until stack.size()==1 -> pop Andrew (size becomes2), then pop? Actually we need stack.size() ==1, so we pop two times? Let's simulate: After Andrew, stack is [John, Robert, Andrew] (size3). For Nancy depth=1, we need size=1. So while stack.size() > 1: pop. So pop Andrew (size2), pop Robert (size1). Now stack = [John]. Parent = stack.top() (since depth>0, parent = John). Push Nancy -> [John, Nancy]. Good.
Thus this parsing works.
Now after building tree, we need to process m statements. Each statement has format: "X is a child of Y." etc. Since names consist only of alphabetic characters, but they could be multi-word? No, name is a string of alphabetic characters (only letters). So a single token. So we can parse statement by splitting into words. However, the statement includes punctuation like period. The format ends with a period. We need to extract X and Y and the relation type. The relation type can be: "child", "parent", "sibling", "descendant", "ancestor". However there are articles: "a child", "the parent", "a sibling", "a descendant", "an ancestor". But the wording: "X is a child of Y." or "X is the parent of Y." or "X is a sibling of Y." or "X is a descendant of Y." or "X is an ancestor of Y." So we need to parse the third word? Actually statement pattern: first word is X, second word is "is", third word is article: "a" or "the" or "an", fourth word is relationship: "child"/"parent"/"sibling"/"descendant"/"ancestor", fifth word "of", sixth word Y (without period?), then period. So Y includes the period? Actually Y is a name followed by period. So we need to remove trailing period.
Simpler: We can read the entire line, then split by spaces. The number of parts will be either 6 or 7? Let's see: "X is a child of Y." That splits into: [X, is, a, child, of, Y.] Actually Y. includes period. So length 6. "X is the parent of Y." -> [X, is, the, parent, of, Y.] length 6. "X is an ancestor of Y." -> [X, is, an, ancestor, of, Y.] length 6. So always 6 tokens. The relation is the fourth token? Actually the relationship is the combination of third and fourth? But the third token is article: "a", "the", "an". The fourth token is the relationship word. However, "parent" vs "child" vs "sibling" vs "descendant" vs "ancestor". So we can just check the fourth token to determine relation type. But note that for "the parent", the fourth token is "parent". For "a child", fourth token is "child". For "a sibling", "sibling". For "a descendant", "descendant". For "an ancestor", "ancestor". So we can simply check the fourth token: "child", "parent", "sibling", "descendant", "ancestor". Good. Also note that Y token ends with period. We need to remove the trailing period. So Y = tokens[5] without last character (if it ends with '.'). Or we can extract substring up to the period.
We should also consider case where there is trailing whitespace? They said no redundant spaces at beginning and end, so no.
Thus parse: tokens = split(line). X = tokens[0]. rel = tokens[3] (the relationship word). Y = tokens[5]; if Y.back() == '.' then Y.pop_back().
Now evaluate.
Implementation details:
We'll have a map<string, int> nameToIdx.
Node struct: name, parent index (-1 for root), vector children.
For quick ancestor check: function is_ancestor(anc, desc): climb from desc to root, checking if anc appears.
But we might need to be careful about performance: n <= 1000, m <= 1000, so worst-case depth could be near n (like a chain), so climbing each query could be O(n) = 1000, total 1e6, fine.
Alternatively, we can precompute depth and maybe use Euler tour or something, but not needed.
Check relationships:
child: parent[ X ] == Y
parent: parent[ Y ] == X
sibling: X != Y and parent[X] != -1 and parent[Y] != -1 and parent[X] == parent[Y] (but root's parent is -1; but if both are root? root is only one; they are different, so no sibling)
descendant: is_ancestor(Y, X) (Y ancestor of X)
ancestor: is_ancestor(X, Y)
We must output "True" or "False" with capital first letter and rest lowercase. And after each dataset, output an empty line.
Edge cases: The input may have extra blank lines? The problem statement says each line of the input has less than 70 characters. There might be blank lines? Usually not. But we need to handle reading lines that may have leading spaces. So we need to use getline to read entire lines. However, careful: after reading n and m with cin, we need to consume the newline before reading the family tree lines. Since we'll use getline, we should be careful.
We'll read n and m. If both zero, break.
Then we need to read n lines of family tree. They may contain leading spaces. We'll use getline(cin, line). But we must ensure that we don't skip empty lines erroneously. Typically, after reading n and m, there is a newline. We can call cin.ignore() to discard the newline before getline, or we can use getline after reading integers; but if we use getline directly, the first getline will read the rest of the line (which might be empty if the integer line ends with newline and no extra spaces). Actually after cin >> n >> m, the newline remains. So getline will read an empty line. To avoid that, we can call cin.ignore() to skip the newline. But there might be cases where there are trailing spaces? Safer: after reading n and m, we call getline to read the rest of the line (which should be empty) and discard it. But then subsequent getline will read the first family line. Alternatively, we can use getline for everything: read n and m as tokens from a line, but they are given on one line. So we could read a line and parse n,m. However, simpler: use cin >> n >> m; then cin.ignore(1000, '\n') to skip newline. Since lines are less than 70, 1000 is safe.
Then for i in [0,n): getline(cin, line). This line includes leading spaces.
We'll process each line: count leading spaces by iterating until non-space char. But what if the line is empty? That shouldn't happen because each line contains a name, at least one alphabetic character. So line will have at least one character after spaces? Actually could be spaces then name; but name is at least one character, so line length > spaces.
Implementation: count spaces = 0; while (spaces < line.length() && line[spaces] == ' ') ++spaces; Then name = line.substr(spaces). Possibly we also need to strip trailing spaces? They said no redundant spaces at the end, so fine.
Now depth = spaces? But note: Are they counting each space as one indent? Usually the indent is number of spaces. However, could there be multiple spaces per indent? The problem says "indented with one more space than the parent" and "indented with k spaces" suggests that the number of spaces directly equals the depth. For root depth0 has 0 spaces, children have 1 space, grandchildren have 2 spaces, etc. So depth = number of leading spaces. Yes.
So parse with stack.
After building tree, we read m statements. Each statement line: getline(cin, stmt). We need to parse. We'll split by spaces. Could use stringstream or manual find.
We'll split: istringstream iss(stmt); vector tokens; string token; while (iss >> token) tokens.push_back(token); This splits by spaces, and it will drop any leading/trailing spaces, but there are none. However, tokens[5] will be "Y." with period. We'll remove period: if (tokens[5].back() == '.') tokens[5].pop_back();.
Then get X = tokens[0], Y = tokens[5], rel = tokens[3].
Now evaluate.
Potential pitfall: There could be names with same as keywords? No, names are alphabetic only, but could be "child" etc. But statements guarantee that X and Y are names from family tree, so they are actual names, not keywords. So splitting is safe.
We should also ensure that the relationship token is exactly as expected.
Now we output True/False for each statement.
After finishing all statements for a dataset, output an empty line (i.e., a blank line). In the example output, after the first dataset there is a blank line, then next dataset's output begins, then after second dataset there is also a blank line? The output shows after first dataset's 5 lines, there is an empty line, then "True" (from second dataset) then an empty line after that. So yes, after each dataset, an empty line.
Now we need to test with given examples.
Example input:
6 5
John
Robert
Frank
Andrew
Nancy
David
Robert is a child of John.
Robert is an ancestor of Andrew.
Robert is a sibling of Nancy.
Nancy is the parent of Frank.
John is a descendant of Andrew.
2 1
abc
xyz
xyz is a child of abc.
0 0
Wait the second dataset: lines: abc and then xyz (indented with a space). So depth: abc depth0, xyz depth1. So xyz is child of abc. Output True.
But the first dataset: there are 6 names. The statements:
Robert is a child of John. => true.
Robert is an ancestor of Andrew. => true (Robert is parent of Andrew? Actually Robert's children: Frank and Andrew. So yes ancestor includes parent).
Robert is a sibling of Nancy. => true (both children of John).
Nancy is the parent of Frank. => false (Nancy is not parent of Frank; Frank is child of Robert).
John is a descendant of Andrew. => false.
Outputs: True True True False False, then blank line, then True, then blank line.
In example output they also have an extra blank line after second dataset.
Also note: There is a second example input that seems identical? Actually second example input in the problem statement looks similar but without proper indentation? Wait there are two examples provided? Actually the problem statement shows two example inputs and outputs. The first example input includes proper indentation with spaces. The second example input (under the same "Examples" heading) is perhaps a misformat? Actually they show:
Input
6 5
John
Robert
Frank
Andrew
Nancy
David
Robert is a child of John.
Robert is an ancestor of Andrew.
Robert is a sibling of Nancy.
Nancy is the parent of Frank.
John is a descendant of Andrew.
2 1
abc
xyz
xyz is a child of abc.
0 0
Output
True
True
True
False
False
True
But this second example seems to have no indentation? The family tree lines after "6 5" are: John, Robert, Frank, Andrew, Nancy, David. Each on a separate line with no leading spaces. But that would mean all are depth0? That would be invalid because then they would all be root? However, the statements may still be parsed? But they still produce same output? Actually output is the same as first example? That's weird. Possibly the problem statement is showing two versions: one with spaces, one without? But they both produce same output? That can't be; maybe the formatting got lost: The second example likely also has indentation but due to plain text, spaces are not visible. Actually typical in problem statements, indentation is shown by spaces, but in the plain text they might be omitted. The first input example in the statement shows explicit spaces: " John" then " Robert" etc. The second input example may have lost spaces due to copy? But both outputs are the same. However, the output for second input example shows only "True" after the blank line, not the five lines? Actually they show:
Output
True
True
True
False
False
True
Wait that's identical to first output? Yes. So maybe they intended both inputs to be the same but one has spaces explicitly, the other not. We'll ignore.
Thus our parsing based on spaces is correct.
Now let's think about potential pitfalls.
Names are case-sensitive? Usually yes, as given.
There might be names that are same as "child", but that would cause confusion in parsing? But names are only alphabetic, but keywords are also alphabetic. So a name could be "child". However, statements guarantee that X and Y are names from family tree. So if a person's name is "child", the statement would be: child is a child of Y. Then tokens[0] = "child". That's fine. The relationship token tokens[3] is "child"? Actually token at index 3 is the relationship word, not the name. So even if name is "child", it's token[0] or token[5]. So no conflict. However, there is a possibility that the name includes spaces? No, names are only alphabetic characters, so no spaces. So splitting works.
The article "an" appears only before "ancestor". So token[2] could be "a", "the", "an". We don't need it.
Need to ensure that we read the entire line for statement, which may include spaces between words, but no leading/trailing spaces. Using getline and stringstream is fine.
The statements may include a period at end. We remove it.
Now about building the tree: Using stack of indices.
Implementation steps:
Define struct Node {
string name;
int parent;
vector children;
int depth; // maybe not needed after building, but we could store depth.
};
for i=0..n-1:
string line;
getline(cin, line);
int spaces = 0;
while (spaces < line.size() && line[spaces] == ' ') spaces++;
string name = line.substr(spaces);
int depth = spaces; // because root depth0
code
// pop stack until its size equals depth
while (depthStack.size() > depth) {
depthStack.pop_back();
}
int parent_idx = -1;
if (!depthStack.empty()) {
parent_idx = depthStack.back();
}
int idx = nodes.size();
nodes.push_back(Node{name, parent_idx, vector<int>(), depth});
name2idx[name] = idx;
if (parent_idx != -1) {
nodes[parent_idx].children.push_back(idx);
}
depthStack.push_back(idx);
After reading all lines, we have tree.
Now process statements:
For i=0..m:
string stmt;
getline(cin, stmt);
istringstream iss(stmt);
vector tokens;
string token;
while (iss >> token) tokens.push_back(token);
// tokens size should be 6
if (tokens.size() != 6) { // maybe error, but assume correct.
// handle? but not.
}
string X = tokens[0];
string Y = tokens[5];
// remove trailing '.' from Y
if (Y.back() == '.') Y.pop_back();
string rel = tokens[3]; // relationship word
code
// get indices
int idxX = name2idx[X];
int idxY = name2idx[Y];
bool result;
if (rel == "child") {
// X is a child of Y => parent[X] == Y
result = (nodes[idxX].parent != -1 && nodes[nodes[idxX].parent].name == Y);
// or compare parent idx: nodes[idxX].parent == idxY
// Actually we can compare indices: nodes[idxX].parent == idxY
// This is better.
} else if (rel == "parent") {
result = (nodes[idxY].parent == idxX);
} else if (rel == "sibling") {
// X is a sibling of Y => share same parent, both not root, and X != Y
int parentX = nodes[idxX].parent;
int parentY = nodes[idxY].parent;
result = (parentX != -1 && parentY != -1 && parentX == parentY && idxX != idxY);
} else if (rel == "descendant") {
// X is descendant of Y => Y is ancestor of X
result = isAncestor(idxY, idxX);
} else if (rel == "ancestor") {
result = isAncestor(idxX, idxY);
} else {
// Shouldn't happen
result = false;
}
cout << (result ? "True" : "False") << endl;
Define isAncestor(a, d) function: while (d != -1) { if (d == a) return true; d = nodes[d].parent; } return false;
Make sure that a and d are valid indices.
Now after all statements, print an empty line: cout << endl;
But careful: The last dataset should also have an empty line after its output. The example shows a blank line after the second dataset as well. So we always output an empty line after each dataset, including after the last? The problem says: "The output for each data set should be followed by an empty line." So yes, after each dataset output an empty line, including after the last. So we need to print a blank line after finishing all statements for a dataset. Typically we do: after processing dataset, output a blank line (cout << endl;). But if there are multiple datasets, after last dataset we also output a blank line. That matches.
Potential issue: The blank line should be just a newline, no extra spaces. Using cout << endl; will output newline. If we already printed the last statement line with endl, then we output another endl, we get a blank line. That's correct.
Now need to test with sample input.
Let's simulate with sample input:
First dataset:
n=6,m=5.
Lines:
1: "John" -> spaces=0, depth=0, stack empty, parent=-1, push idx0.
2: " Robert" -> spaces=1 (there is a space before Robert), depth=1, stack size=1 > depth? 1>1? Actually size=1, depth=1 => while size>depth? size=1, depth=1 => false, no pop. parent = stack.back() idx0. push idx1.
3: " Frank" -> spaces=2, depth=2, stack size=2 >2? false, parent = idx1, push idx2.
4: " Andrew" -> spaces=2, depth=2, stack size=3 >2 => pop (idx2). size becomes2, equals depth2. parent = stack.back() idx1. push idx3.
5: " Nancy" -> spaces=1, depth=1, stack size=3 >1? pop until size=1: pop idx3 (size2), pop idx1? Actually after pushing Andrew, stack = [0,1,3]. size=3. while size>1: pop idx3 => size2; while size>1? size2>1 => pop idx1 => size1; Now size==1, depth=1. parent = stack.back() idx0. push idx4.
6: " David" -> spaces=2, depth=2, stack size=2 >2? false, parent = stack.back() idx4. push idx5.
Tree built correctly.
Statements:
Robert is a child of John: parent(idx1)=0 => true.
Robert is an ancestor of Andrew: ancestor(1,3) => check: Andrew's parent=1 => true.
Robert is a sibling of Nancy: parent both 0 => true.
Nancy is the parent of Frank: parent(Frank)=1 !=4 => false.
John is a descendant of Andrew: ancestor(3,0)? false.
One more nuance: The input lines for family tree may contain tabs? The problem says spaces, not tabs. So we assume spaces.
Now about reading lines: We must be careful that the lines after n and m may include empty lines? But the problem says no. But just in case, we need to handle if getline returns empty line? Possibly there might be a blank line between datasets? The input terminates with 0 0, but there may be no blank lines. We'll assume not.
We'll read n and m with cin. Then ignore newline. Then for i in range(n): getline(cin, line). That should read the lines even if they have leading spaces. However, what if some line is exactly 70 chars and includes spaces? getline will capture the entire line.
Now after reading n lines, we read m statements with getline. That will read the statements lines. After that, next dataset starts with two integers. But note: after reading m statements, there might be a newline before the next dataset's n m line. That newline will be consumed by the next cin >> n >> m? cin >> skips whitespace, so it's fine. But we need to be careful: After reading all statements, we may still have a newline pending? Actually we use getline for statements; the last statement line will include its newline; getline consumes that newline. So after finishing loop, the input pointer is at the beginning of the next line (which could be the next dataset's n m). So we can just go to top of loop and read n,m using cin >> n >> m. However, cin >> will skip leading whitespace (including newline). So it's fine.
But one subtlety: After reading the last dataset's statements, the next line will be "0 0". That will be read by cin >> n >> m. So works.
Now implement.
Potential pitfalls:
The map name2idx: ensure we use correct indices.
For sibling: They may be half-siblings? But the tree only includes one parent. The problem says: "the professor excluded some people from the family trees so that no one had both parents in a family tree." So each person has at most one parent shown, and that parent is the one in the tree. So siblings share the same parent (the one in the tree). So half-siblings by other parent not shown, but they'd be considered siblings if they share the same parent? Since only one parent is recorded, they are considered siblings if they share that parent. That matches the definition: "X is a sibling of Y." In typical family trees, siblings share at least one parent. Since only one parent is recorded, they are considered siblings if they share that parent. So our check is correct.
For descendant and ancestor: This is defined by following parent links. It includes direct child and further. So correct.
Now consider test: root is ancestor of everyone else. So statements like "John is an ancestor of David" would be true.
Edge case: If X is same as Y? The problem says "X and Y are different names in the family tree." So we don't have to handle same name. Good.
Now the code.
Let's write in C++.
Implementation details:
Use vector nodes.
Use unordered_map<string, int> name2idx.
Define function bool isAncestor(int anc, int desc).
Now careful: The depth is number of leading spaces. But what if there are multiple spaces per indent? As said, each additional indent is one more space. So depth equals spaces.
Now test with second sample (if it had no spaces, but that's not a valid test). So it's fine.
Now about memory: n up to 1000, fine.
Now output: For each statement, print "True" or "False".
Now about reading lines: We need to count spaces correctly. However, if we use getline, it reads the line as a string. Leading spaces are included. So counting spaces: use line.find_first_not_of(' ') to get first non-space. But careful: The line could consist entirely of spaces? Not possible because there is a name. So first_non_space = line.find_first_not_of(' '); if first_non_space == string::npos, that would be empty line; but not happen. Then spaces = first_non_space; name = line.substr(first_non_space). But note that find_first_not_of returns index, but if first char is not space, it returns 0, spaces =0. Good.
But also we can just count manually: spaces = 0; while (spaces < line.length() && line[spaces] == ' ') spaces++; Then name = line.substr(spaces). That works.
Now the stack: We'll store indices.
Pseudo:
vector stackIdx; // path from root to current
for i=0; i<n; i++) {
string line;
getline(cin, line);
int spaces = 0;
while (spaces < line.length() && line[spaces] == ' ') spaces++;
string name = line.substr(spaces);
int depth = spaces;
while (stackIdx.size() > depth) {
stackIdx.pop_back();
}
int parentIdx = -1;
if (!stackIdx.empty()) {
parentIdx = stackIdx.back();
}
int idx = nodes.size();
nodes.push_back({name, parentIdx, {}, depth}); // maybe children later
name2idx[name] = idx;
if (parentIdx != -1) {
nodes[parentIdx].children.push_back(idx);
}
stackIdx.push_back(idx);
}
Now we have tree.
Now process m statements:
for (int i=0; i<m; i++) {
string line;
getline(cin, line);
istringstream iss(line);
vector tokens;
string token;
while (iss >> token) {
tokens.push_back(token);
}
if (tokens.size() != 6) { // maybe something wrong, but ignore.
// Could be due to period? No, still 6 tokens because Y. is one token.
}
string X = tokens[0];
string Y = tokens[5];
if (Y.back() == '.') Y.pop_back();
string rel = tokens[3];
code
// get indices
if (name2idx.find(X) == name2idx.end() || name2idx.find(Y) == name2idx.end()) {
// According to problem, X and Y are names in family tree, so should exist.
// but handle gracefully: false.
}
int idxX = name2idx[X];
int idxY = name2idx[Y];
bool ans = false;
if (rel == "child") {
if (nodes[idxX].parent != -1 && nodes[idxX].parent == idxY)
ans = true;
} else if (rel == "parent") {
if (nodes[idxY].parent != -1 && nodes[idxY].parent == idxX)
ans = true;
} else if (rel == "sibling") {
int pX = nodes[idxX].parent;
int pY = nodes[idxY].parent;
if (pX != -1 && pY != -1 && pX == pY && idxX != idxY)
ans = true;
} else if (rel == "descendant") {
ans = isAncestor(idxY, idxX);
} else if (rel == "ancestor") {
ans = isAncestor(idxX, idxY);
}
cout << (ans ? "True" : "False") << endl;
}
After m statements, print endl for blank line.
Now let's test with given sample.
First dataset output as expected.
Second dataset output "True" then blank line.
Now consider tricky cases:
If depth is more than one space, we count spaces exactly. That's fine.
Statements may have extra spaces? They said no redundant spaces at beginning or end, but there is exactly one space between words. So split works.
Period removal: Y may have a period at the end. But what if Y ends with a period as part of name? Names are only alphabetic, so no period. So safe.
Ensure that Y token after removing period is exactly the name.
Note: In case of "ancestor", token[3] is "ancestor" (since "an" is token[2]). So rel = "ancestor" works.
For "parent", token[3] is "parent". For "child", "child". For "sibling", "sibling". For "descendant", "descendant". Good.
Now about the reading order: We need to be careful when mixing cin >> and getline. We'll do:
while (true) {
int n, m;
cin >> n >> m;
if (n == 0 && m == 0) break;
cin.ignore(1000000, '\n'); // ignore the rest of the line after n and m
code
// read n lines
for (int i=0; i<n; i++) {
string line;
getline(cin, line);
// parse...
}
// read m statements
for (int i=0; i<m; i++) {
string stmt;
getline(cin, stmt);
// process...
}
// after dataset, output blank line
cout << endl;
}
But we must also output the results for statements before the blank line. So after processing each statement we output True/False. Then after the for loop, output endl.
Now check if after the last dataset we also output an empty line. That's fine.
Now potential pitfalls:
The input may have blank lines between datasets? Typically not, but if there were, our reading with cin >> n >> m would skip leading whitespace, so it would skip blank lines. Then after reading n and m, we call cin.ignore to skip the newline after the integers. However, if there is a blank line before the next dataset's numbers, it's not an issue because cin >> n >> m skips whitespace. But if there is a blank line after the previous dataset's statements, it would be consumed by getline? Actually after reading m statements, we would have consumed exactly m lines. The next line should be the next dataset's n m. If there is an extra blank line, then getline would read that blank line as a statement? But problem says input is strict. So we can assume not.
However, some judges may have trailing spaces in lines? But they said no redundant spaces at end. So safe.
Now we should test with a few custom cases:
Case 1: Simple chain: n=3, root A, child B, child C. Input:
A
B
C
Then statements: "B is a child of A" -> True; "C is a descendant of A" -> True; "C is a sibling of B" -> False (different parent). etc.
Our parsing: For line " B": spaces=1 depth1, stack after root size=1, depth=1 => no pop, parent A, push B. Next " C": spaces=2 depth2, stack size=2, depth=2 => no pop, parent B, push C. Good.
Case 2: Siblings with different depths later: root A, child B, child C, grandchild D under B. Input:
A
B
D
C
Parsing: After reading B, stack [A,B]. After reading D, depth2, stack [A,B,D]. After reading C, depth1, pop until size=1: pop D, pop B? Actually stack size=3, depth=1 => while size>1: pop D (size2), pop B? size2 >1 => pop B (size1). Now parent = A. push C. So C is child of A. That's correct.
Now test for sibling detection: B and C are siblings? They share parent A => yes.
Now for descendant: D is descendant of A? yes.
Now ancestor: A is ancestor of D? yes.
Now for "D is a sibling of C"? false because different parents.
Works.
Now consider edge: Root has no parent. Statement like "John is a child of ?" might appear but Y is different, so it will be false if Y is not the parent. But if Y is root? It could be. Our child check: parent[idxX] == idxY. If idxX is root, parent is -1, so false. Good.
Sibling: root and someone else: root parent -1, other parent something, not equal, false. So no issue.
Now isAncestor function: If anc == desc? That would be true if same? But statements guarantee X and Y are different names. So we won't get same. But in the code, if anc == desc, isAncestor would return true. But the problem says they are different, so we don't need to handle, but it's okay.
Now implement isAncestor:
bool isAncestor(int anc, int desc) {
while (desc != -1) {
if (desc == anc) return true;
desc = nodes[desc].parent;
}
return false;
}
Now we need to ensure that nodes vector is accessible. We'll define it globally or per dataset.
Now coding.
Now note: The input lines for family tree might have leading spaces that are not necessarily the exact count? But we count each space as one indent. So depth = number of spaces.
Now I want to verify with the sample input that has proper spacing. In the sample, " Robert" has one leading space, " Frank" has two spaces. But sometimes there might be multiple spaces representing indent of 2? They said "indented with one more space than the parent." So each level adds exactly one space? Not necessarily exactly one: they might use multiple spaces for readability? The example shows: " Robert" (one space), " Frank" (two spaces). So each level adds exactly one space relative to parent. But the problem statement: "The children of a person are indented with one more space than the parent." So indeed each child is indented with exactly one more space than its parent. Therefore, the depth difference is exactly 1. But the indentation can be more than one space per level if there are multiple spaces? Wait, they said "one more space". So if parent has k spaces, child has k+1 spaces. So depth = number of leading spaces. So that matches.
Thus we can count spaces directly.
Now also note: The line may have trailing spaces? They said no redundant spaces at the end. So fine.
Now about reading: getline will include the newline? No, getline discards newline. So line contains the content without newline. So counting spaces is correct.
Now let's consider the second example input in the problem statement (the one without visible spaces). In that input, the family lines are:
John
Robert
Frank
Andrew
Nancy
David
This would be parsed as all depth0, causing them all to be root? That would not match statements. But the statements are the same and output same? That would be contradictory. So likely the second example is just a formatting issue in the problem statement where spaces were not displayed. So we ignore.
Now we are good.
One more nuance: The problem says: "No name appears twice in the same family tree." So names unique.
Now we must ensure we handle the case where n and m up to 999, but statements count m may be up to 999. Our code is O(n + m * depth) which is fine.
Now write final code.
But we need to be careful about reading: In some judges, using getline after cin >> might skip first line if we don't ignore. We will.
Now I think the solution is correct.
However, I want to consider if there could be tricky indentation using tabs? The problem says spaces, so fine.
Now final answer: We'll output exactly as required.
We should also consider that after printing the results for each dataset, we need an empty line. So after the for loop for statements, we do cout << endl; This prints an extra newline. However, after the last dataset, we also output an empty line. That's fine.
But ensure we don't output an extra blank line at the very end? Some judges are okay with trailing blank line. The problem explicitly says "The output for each data set should be followed by an empty line." So it's required. So we must output it. Usually judges ignore trailing whitespace, but it's specified, so we comply.
Now consider test when m=0? It says m>0? Actually they said m (0 < m < 1000) so m >0. So there will always be statements. But if m=0? The spec says 0 < m < 1000, so m at least 1. But they could have m=0? The input says 0 < m < 1000, but maybe they could? But safe to handle m=0: if m=0, we still output just a blank line after dataset? But since it's >0, we can ignore.
Now about the case where n could be 0? They say 0 < n < 1000. So n>=1.
Now all set.
Now we need to produce code.
Potential improvements: Use a function to parse line and compute depth.
Edge Cases: Suppose a line has leading spaces but the name starts after spaces. But what if there are multiple spaces and the line length is large? It's fine.
Now double-check: In our parsing, we treat depth = number of leading spaces. But is it always the case that depth exactly equals the number of spaces? Yes, because root has 0 spaces, child has 1, grandchild 2, etc. So depth = spaces.
Now the while loop: while (stackIdx.size() > depth) pop. But note: stackIdx.size() corresponds to the depth of the last node + 1? Actually stack holds the current path: root at index0 depth0, its child at index1 depth1, etc. So size = current depth + 1 (if we have nodes up to current depth). After processing a node, we push it, so size becomes new depth + 1. So for a new node with depth d, we need the stack to contain the ancestors up to depth d-1. That means the stack size should be d (since that would have nodes at depths 0..d-1). But after popping, we want stack size = d? Let's think: When we are about to add a node of depth d, the stack currently contains the path to the previous node. After popping until stack.size() == d, the top will be node at depth d-1 (since indices: 0..d-1). So parent is stack.back(). Then after pushing, stack size becomes d+1, which is consistent.
Thus condition while (stack.size() > depth) is correct.
But wait, depth is the number of leading spaces. For root depth=0, stack initially empty, size=0, depth=0 => no pop, parent = none, push => size=1.
For depth=1, stack size currently 1, depth=1 => while size>1? false, parent = stack[0], push => size=2.
For depth=2 again after depth=2, stack size 3, depth=2 => while size>2 true: pop => size=2, then while condition false, parent = stack[1] (depth1), push size=3. Works.
For depth=1 after depth=2, stack size 3, depth=1 => while size>1 true: pop => size2 (pop idx2), still size2>1 true: pop => size1 (pop idx1), now size1==depth1 => parent = stack[0] (depth0). Works.
So condition is correct.
Now in code we need to implement isAncestor. Could also use depth to speed up: but not necessary.
Now coding.
One more nuance: The input might contain lines with spaces that are not multiples? But as said, each level adds exactly one space, so depth integer is fine.
Now we can write.
After finishing, test with sample.
But I realize something: In the sample, the family tree lines are as follows:
John
Robert
Frank
Andrew
Nancy
David
In the text, there is a space before Robert, two spaces before Frank and Andrew, one space before Nancy, two spaces before David. That matches.
But if we copy-paste from the problem statement, sometimes spaces are lost. But our program reading from input will see the spaces.
Now test with code in mind.
Now let's consider a tricky case: The line could have more than one space but still represent a depth increase? Actually if parent has k spaces, child has exactly k+1 spaces. So it's strictly one more. So depth is exact number of spaces.
Now are there cases where the indentation uses tabs? The problem says spaces, so no.
Now finalize.
But there is one more nuance: The family tree may contain people with same name? No, names are unique.
Now we need to handle large input. Use getline and stringstream.
Now ensure that after reading n lines, we correctly set parent relationships. We also may store depth for maybe debugging but not needed.
Now implement.
Will there be any case where a person's parent is not the most recent node with depth-1? According to the description, the family tree is constructed such that each person's parent is the last person with one less indentation. And they guarantee that the parent exists. So our method is valid.
Now write the code.
We'll also add a quick check for statement parsing: token count could be 6. If something else, we might need to handle but assume not.
Now think about possible whitespace in name? Name only alphabetic, so fine.
Now finalize code.
Implementation:
#include
#include
#include
#include
#include <unordered_map>
using namespace std;
struct Node {
string name;
int parent;
vector children;
int depth;
Node(string n, int p, int d) : name(n), parent(p), depth(d) {}
};
bool isAncestor(int anc, int desc, const vector& nodes) {
while (desc != -1) {
if (desc == anc) return true;
desc = nodes[desc].parent;
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m;
bool firstDataset = true;
while (cin >> n >> m) {
if (n == 0 && m == 0) break;
cin.ignore(100000, '\n'); // ignore rest of line
code
vector<Node> nodes;
unordered_map<string, int> name2idx;
vector<int> stackIdx; // holds indices along the current path
// read family tree
for (int i = 0; i < n; ++i) {
string line;
getline(cin, line);
int spaces = 0;
while (spaces < line.length() && line[spaces] == ' ') ++spaces;
string name = line.substr(spaces);
int depth = spaces;
// pop stack until its size equals depth
while (stackIdx.size() > depth) {
stackIdx.pop_back();
}
int parentIdx = -1;
if (!stackIdx.empty()) {
parentIdx = stackIdx.back();
}
int idx = nodes.size();
nodes.emplace_back(name, parentIdx, depth);
name2idx[name] = idx;
if (parentIdx != -1) {
nodes[parentIdx].children.push_back(idx);
}
stackIdx.push_back(idx);
}
// process statements
for (int i = 0; i < m; ++i) {
string line;
getline(cin, line);
istringstream iss(line);
vector<string> tokens;
string token;
while (iss >> token) {
tokens.push_back(token);
}
if (tokens.size() != 6) {
// Should not happen, but just skip? We'll assume valid.
continue;
}
string X = tokens[0];
string Y = tokens[5];
// Remove trailing period from Y
if (!Y.empty() && Y.back() == '.') {
Y.pop_back();
}
string rel = tokens[3]; // child, parent, sibling, descendant, ancestor
// find indices
auto itX = name2idx.find(X);
auto itY = name2idx.find(Y);
// according to problem, both exist
if (itX == name2idx.end() || itY == name2idx.end()) {
cout << "False" << endl;
continue;
}
int idxX = itX->second;
int idxY = itY->second;
bool result = false;
if (rel == "child") {
if (nodes[idxX].parent == idxY) {
result = true;
}
} else if (rel == "parent") {
if (nodes[idxY].parent == idxX) {
result = true;
}
} else if (rel == "sibling") {
int pX = nodes[idxX].parent;
int pY = nodes[idxY].parent;
if (pX != -1 && pY != -1 && pX == pY && idxX != idxY) {
result = true;
}
} else if (rel == "descendant") {
result = isAncestor(idxY, idxX, nodes);
} else if (rel == "ancestor") {
result = isAncestor(idxX, idxY, nodes);
} else {
// unknown relation, treat as false
}
cout << (result ? "True" : "False") << endl;
}
// blank line after dataset
cout << endl;
}
return 0;
}
Now test with sample input:
Input:
6 5
John
Robert
Frank
Andrew
Nancy
David
Robert is a child of John.
Robert is an ancestor of Andrew.
Robert is a sibling of Nancy.
Nancy is the parent of Frank.
John is a descendant of Andrew.
2 1
abc
xyz
xyz is a child of abc.
0 0
Run mentally:
First dataset: prints 5 lines as expected, then endl. Second dataset prints True then endl then blank line? Actually after second dataset statements, we print True then endl, then after the for loop we print another endl, so there will be a blank line after the True. That matches sample output: They show:
True
True
True
False
False
True
Yes there is an empty line after the first dataset (a blank line) and then after the second dataset's "True" there is an empty line as well (the blank line after True). So our output will be:
True\nTrue\nTrue\nFalse\nFalse\n\nTrue\n\n? Wait let's be precise.
Our first dataset: after processing 5 statements, we output 5 lines each with "True/False" and newline. Then after the for loop we output cout << endl; => this adds an extra newline. So output:
True\n
True\n
True\n
False\n
False\n
\n
Now second dataset: read, then process 1 statement: output True\n. Then after loop, output endl => another \n. So overall:
True\n
True\n
True\n
False\n
False\n
\n
True\n
\n
That matches sample: after first dataset's five lines, there is a blank line (the extra \n), then "True", then blank line. So good.
Now test with second dataset with m=1 and n=2. Works.
Now we should consider any pitfalls: The getline reading for the family tree lines may read empty line if there is a stray newline. But we trust input.
Now about leading spaces: Our counting loop uses ' ' character. That's fine.
One more potential nuance: There might be lines where the name contains spaces? No.
Now check for statement parsing: Suppose the statement is "X is a child of Y." The tokens[5] is "Y." we remove the period. Good.
But what about "X is an ancestor of Y." tokens[5] "Y." same.
Now about "X is the parent of Y." tokens[5] "Y." same.
Now about "X is a sibling of Y." tokens[5] "Y." same.
Thus consistent.
Now I think it's correct.
One more corner: The input might have trailing spaces after the name? They said no redundant spaces at the end. So fine.
Now about the while (stackIdx.size() > depth) condition: depth is number of spaces. But suppose the line has depth > stack.size()? Could that happen? They guarantee that depth is at most previous depth+1, but previous depth is stack.size()-1 (since stack.size() = previous depth +1). So depth <= previous depth+1 => depth <= (stack.size()-1)+1 = stack.size(). So depth <= stack.size(). But we need to pop only if stack.size() > depth. If depth == stack.size(), we don't pop. That's fine. But what if depth > stack.size()? That would be depth == stack.size()+? Actually depth could be greater than stack.size()? The condition says at most k+1, where k is previous depth. previous depth = stack.size() - 1. So max depth = stack.size(). So depth cannot exceed stack.size(). So stack.size() > depth or equal. So the condition while (stack.size() > depth) is sufficient; we never need to handle depth > stack.size(). Good.
Now about the root: depth = 0, stack is empty initially, depth <= stack.size()? stack.size()=0, depth=0 => no pop, works.
Now about building children: we may store children but not needed. We could skip children list to save memory, but it's fine.
Now about the isAncestor function: We need to pass nodes as const reference. Good.
Now about using unordered_map: ensure include <unordered_map>.
Now about using emplace_back: We'll need to have constructor defined. In Node struct, we provided a constructor with parameters. So emplace_back works.
If we want to avoid constructor, we could use push_back with Node(name, parentIdx, depth). But emplace_back is fine.
Now about the initial line reading: we used cin.ignore(100000,'\n') to discard the rest of the line after n m. But there might be trailing spaces? Not needed.
Now about name length: less than 20 characters, so fine.
Now about statement lines: less than 70 characters, so fine.
Now about multiple datasets: we need to reset data structures each dataset.
Now final code.
But I realize one subtlety: When we read the family tree lines, we need to count leading spaces. But what if there are lines that have leading spaces that are not a multiple of 1? Since each indent is exactly one space, it's fine. However, what if the input uses multiple spaces per indent? For example, root no spaces, child indented by two spaces, grandchild by four spaces? That would be "two more spaces than the parent", but the problem says "one more space". So it's guaranteed to be exactly one more. So depth = number of spaces. So it's fine.
Now also note: The input may have lines that have spaces before the name but also the name could be empty? No.
Now let's consider if the input contains a line with only spaces? Not possible because it contains a name.
Now we should test with a custom case where the tree has many levels and statements. It will be fine.
Now I think we can finalize.
But there is another nuance: The problem says "You can assume that if a name in the family tree is indented with k spaces, the name in the next line is indented with at most k + 1 spaces." This means that depth cannot increase by more than 1, but it can decrease arbitrarily. Our algorithm handles that.
Now all good.
Now answer.
But before final, let's double-check sibling: "X is a sibling of Y." Sibling typically means share at least one parent. Since only one parent is in tree, it's share that parent. So check as above. However, what about half-siblings? If a person had two parents, the professor excluded one so that no one had both parents. So each person has exactly one parent in the tree. So half-siblings are shown as full siblings? Actually if two persons share the same parent in the tree, they are siblings; regardless of whether they have different other parent. So it's correct as per given tree.
Now final code.
Now produce final answer.
But I'd like to also consider a scenario where the root is not the only person with no parent. Because the root is oldest ancestor, so no parent. Other nodes have parent. So sibling relationship will not include root.
struct Node {
string name;
int parent;
vector children; // not strictly needed, but kept for clarity
int depth;
Node(string n, int p, int d) : name(n), parent(p), depth(d) {}
};
// check if 'anc' is an ancestor of 'desc'
bool isAncestor(int anc, int desc, const vector& nodes) {
while (desc != -1) {
if (desc == anc) return true;
desc = nodes[desc].parent;
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
int n, m;
while (cin >> n >> m) {
if (n == 0 && m == 0) break;
cin.ignore(100000, '\n'); // discard the rest of the first line
vector<Node> nodes;
unordered_map<string, int> name2idx;
vector<int> stackIdx; // current path from root
// ----- read the family tree -----
for (int i = 0; i < n; ++i) {
string line;
getline(cin, line);
// count leading spaces = depth
int spaces = 0;
while (spaces < line.size() && line[spaces] == ' ') ++spaces;
string name = line.substr(spaces);
int depth = spaces;
// pop to the correct parent level
while (stackIdx.size() > depth) {
stackIdx.pop_back();
}
int parentIdx = -1;
if (!stackIdx.empty()) parentIdx = stackIdx.back();
int idx = nodes.size();
nodes.emplace_back(name, parentIdx, depth);
name2idx[name] = idx;
if (parentIdx != -1) {
nodes[parentIdx].children.push_back(idx);
}
stackIdx.push_back(idx);
}
// ----- process the statements -----
for (int i = 0; i < m; ++i) {
string line;
getline(cin, line);
istringstream iss(line);
vector<string> tokens;
string token;
while (iss >> token) tokens.push_back(token);
// tokens format: X is [a|the|an] relation of Y.
if (tokens.size() != 6) continue; // should never happen
string X = tokens[0];
string Y = tokens[5];
if (Y.back() == '.') Y.pop_back(); // remove trailing period
string rel = tokens[3]; // child, parent, sibling, descendant, ancestor
// indices are guaranteed to exist
int idxX = name2idx[X];
int idxY = name2idx[Y];
bool ans = false;
if (rel == "child") {
if (nodes[idxX].parent == idxY) ans = true;
}
else if (rel == "parent") {
if (nodes[idxY].parent == idxX) ans = true;
}
else if (rel == "sibling") {
int pX = nodes[idxX].parent;
int pY = nodes[idxY].parent;
if (pX != -1 && pY != -1 && pX == pY && idxX != idxY) ans = true;
}
else if (rel == "descendant") {
ans = isAncestor(idxY, idxX, nodes);
}
else if (rel == "ancestor") {
ans = isAncestor(idxX, idxY, nodes);
}
cout << (ans ? "True" : "False") << '\n';
}
// blank line after each data set
cout << '\n';
}
return 0;