PTA 7-3 愿天下有情人都是失散多年的兄妹 (25 分)
这道题其实是利用了树的层次遍历的思想,建两个队列,将要测试的两个人的五代以内的长辈push进队列,比较两个队列中是否有相同的人出现
注意:一定要定义父母的性别,否则会有几个测试点过不去,因为父母是可以再婚的,可能出现在测试集中
#include <iostream>
#include <queue>
#include <map>
using namespace std;
struct Person
{
char sex=' ';
int father=-1;
int mother=-1;
};
map<int,Person> p;
int Compare(int *a1,int t,int *b1,int c)
{
for(int i=0;i<t;i++)
{
for(int j=0;j<c;j++)
{
if(a1[i]==b1[j])
return false;
}
}
return true;
}
bool Check(Person a,Person b)
{
int a1[32],b1[32],c=0,t=0;
queue<int> Q1,Q2;
if(a.father!=-1)
{
Q1.push(a.father);
a1[t]=a.father;
t++;
}
if(a.mother!=-1)
{
Q1.push(a.mother);
a1[t]=a.mother;
t++;
}
if(b.father!=-1)
{
Q2.push(b.father);
b1[c]=b.father;
c++;
}
if(b.mother!=-1)
{
Q2.push(b.mother);
b1[c]=b.mother;
c++;
}
int Size=Q1.size();
int Size2=Q2.size();
for(int j=0; j<3; j++)
{
for(int i=0; i<Size; i++)
{
int q=Q1.front();
Q1.pop();
if(p[q].father!=-1&&p[q].father!=0)
{
Q1.push(p[q].father);
a1[t]=p[q].father;
t++;
}
if(p[q].mother!=-1&&p[q].mother!=0)
{
Q1.push(p[q].mother);
a1[t]=p[q].mother;
t++;
}
}
for(int i=0; i<Size2; i++)
{
int q=Q2.front();
Q2.pop();
if(p[q].father!=-1&&p[q].father!=0)
{
Q2.push(p[q].father);
b1[c]=p[q].father;
c++;
}
if(p[q].mother!=-1&&p[q].mother!=0)
{
Q2.push(p[q].mother);
b1[c]=p[q].mother;
c++;
}
}
Size=Q1.size();
Size2=Q2.size();
}
if(Compare(a1,t,b1,c)==true)
{
return true;
}
return false;
}
int main()
{
int n,NO;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>NO;
cin>>p[NO].sex>>p[NO].father>>p[NO].mother;
if(p[NO].mother!=-1)
p[p[NO].mother].sex='F';
if(p[NO].father!=-1)
p[p[NO].father].sex='M';
}
cin>>n;
for(int i=0; i<n; i++)
{
int a1,a2;
cin>>a1>>a2;
if(p[a1].sex==p[a2].sex)
{
cout<<"Never Mind"<<endl;
continue;
}
else if(Check(p[a1],p[a2]))
{
cout<<"Yes"<<endl;
}
else
{
cout<<"No"<<endl;
}
}
return 0;
}