Without tree,we can still solve this problem.
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Person
{
string name;
int level;
};
int main()
{
// freopen("C:\\Users\\Frank Wang\\Desktop\\in.txt","r",stdin);
ios_base::sync_with_stdio(0);
// cin.tie(0);
vector<Person> family_tree;
int n,m;
cin>>n>>m;
while(n--)
{
if(cin.get()!='\n') cin.unget();
int s_cnt=0;
while(cin.get()==' ') ++s_cnt;
cin.unget();
Person pe_tmp;
pe_tmp.level=s_cnt;
cin>>pe_tmp.name;
family_tree.push_back(pe_tmp);
}
// for(vector<Person>::iterator it=family_tree.begin();it!=family_tree.end();++it)
// {
// cout<<it->name<<' '<<it->level<<endl;
// }
string name_a,name_b,relation;
while(m--)
{
cin>>name_a;
int count=6;
while(count--) cin.get();
char ch;
cin.get(ch);
if(ch=='c'||ch=='e')
{
relation="child";
}
else if(ch=='s') relation="sibling";
else
{
relation="ancestor";
}
cin.ignore(256,'f');
cin>>name_b;
if(ch=='e'||ch=='d')
{
name_a.swap(name_b);//or swap(name_a,name_b) in <algorithm>,but former is better.
}
// cout<<name_a<<' '<<name_b<<' '<<relation<<endl;
if(relation=="child")
{
vector<Person>::iterator it=family_tree.begin();
for(;it!=family_tree.end();++it)
{
if(it->name==name_b) break;
}
int level_tmp=it->level;
if(it!=family_tree.end()) ++it;
bool flag=1;
while(it!=family_tree.end()&&it->level>level_tmp)
{
if(it->name==name_a&&it->level==level_tmp+2)
{
cout<<"True\n";
flag=0;
break;
}
++it;
}
if(flag) cout<<"False\n";
}
else if(relation=="ancestor")
{
vector<Person>::iterator it=family_tree.begin();
for(;it!=family_tree.end();++it)
{
if(it->name==name_a) break;
}
int level_tmp=it->level;
if(it!=family_tree.end()) ++it;
bool flag=1;
while(it!=family_tree.end()&&it->level>level_tmp)
{
if(it->name==name_b)
{
cout<<"True\n";
flag=0;
break;
}
++it;
}
if(flag) cout<<"False\n";
}
else
{
vector<Person>::iterator it=family_tree.begin();
for(;it!=family_tree.end();++it)
{
if(it->name==name_a) break;
}
int level_tmp=it->level;
vector<Person>::iterator it_tmp=it;
if(it!=family_tree.end()) ++it;
bool flag=1;
while(it!=family_tree.end()&&it->level>=level_tmp)
{
if(it->name==name_b&&it->level==level_tmp)
{
cout<<"True\n";
flag=0;
break;
}
++it;
}
if(flag)
{
if(it_tmp!=family_tree.begin()) --it_tmp;
while(it_tmp!=family_tree.begin()&&it_tmp->level>=level_tmp)
{
if(it_tmp->name==name_b&&it_tmp->level==level_tmp)
{
cout<<"True\n";
flag=0;
break;
}
--it_tmp;
}
}
if(flag) cout<<"False\n";
}
}
}