思路
fat数组保存其直接祖先
#include <bits/stdc++.h>
using namespace std;
const int maxn = 105;
int n, m, fat[maxn], dot[maxn];
string name[maxn], label[maxn], line, s;
int main() {
scanf("%d %d\n", &n, &m);
for(int i = 1; i <= n; i++) {
getline(cin, line, '\n');
int p = line.find_first_not_of("."), k = line.find_first_of("#", p);
dot[i] = p;
if(k == -1) name[i] = line.substr(p);
else name[i] = line.substr(p, k - 1 - p), label[i] = line.substr(k);
for(int j = 0; j < name[i].size(); j++) name[i][j] = tolower(name[i][j]);
int j = i - 1;
while(j >= 1 && dot[j] >= dot[i]) j = j - 1;
fat[i] = j;
}
while(m--) {
vector<string> words;
vector<int> ans;
getline(cin, line, '\n');
stringstream out(line);
while(out >> s) {
if(s[0] != '#') {
for(int i = 0; i < s.size(); i++) s[i] = tolower(s[i]);
}
words.push_back(s);
}
for(int i = 1; i <= n; i++) {
if(s == label[i] || s == name[i]) {
int j = words.size() - 2, k = fat[i];
while(j >= 0 && k != 0) {
if(words[j] == label[k] || words[j] == name[k]) j = j - 1;
k = fat[k];
}
if(j < 0) ans.push_back(i);
}
}
printf("%d", ans.size());
for(int i = 0; i < ans.size(); i++) printf(" %d", ans[i]);
putchar('\n');
}
return 0;
}