题目链接
#include#include #include using namespace std; unordered_map > child,ancestor,sibling,parent,descendant; vector prio(110); int setPrio(string name){ int len = 0; for(len = 0; len < name.length(); len++){ if(name[len] != ' ') break; } prio[len/2] = name.substr(len); return len/2; } void setGen(string name,int num){ if(num == 0) return; //兄弟 for(auto sb:child[prio[num-1]]){ sibling[name].push_back(sb); sibling[sb].push_back(name); } //子女 child[prio[num-1]].push_back(name); //父母 parent[name].push_back(prio[num-1]); //祖先 for(int i = num - 1; i >= 0; i--){ ancestor[name].push_back(prio[i]); //祖先 descendant[prio[i]].push_back(name); //后代 } } bool queryRela(const string &name1,const string &name2,const string &rela){ if(rela == "child"){ for(auto tmp:child[name2]){ if(tmp == name1) return true; } } else if(rela == "parent"){ for(auto tmp:parent[name2]){ if(tmp == name1) return true; } } else if(rela == "sibling"){ for(auto tmp:sibling[name2]){ if(tmp == name1) return true; } } else if(rela == "descendant"){ for(auto tmp:descendant[name2]){ if(tmp == name1) return true; } } else if(rela == "ancestor"){ for(auto tmp:ancestor[name2]){ if(tmp == name1) return true; } } return false; } int main(){ int n,m; cin>>n>>m; getchar(); for(int i = 0; i < n; i++){ string tmp; getline(cin,tmp); int num = setPrio(tmp);//设置等级 tmp = tmp.substr(num*2); setGen(tmp,num);//放入族谱 } while(m--){ string name1,name2,rela,t; cin>>name1>>t>>t>>rela>>t>>name2; if(queryRela(name1,name2,rela)) cout<<"True"; else cout<<"False"; if(m) cout<<'n'; } return 0; }



