比较两棵树中相同深度是否有相同的节点
说白了这就是一道遍历树的题目,dad和mom分别是当前节点的左孩子和右孩子,判断分别以当前节点为根节点的两棵子树中是否有相同的左孩子或右孩子。因为题目中说无乱伦和隔辈成婚现象,所以只需要对两棵子树中对应深度的节点进行两两判断就可以。并且迭代的深度不超过4。
题目中还有一个坑,当读入当前节点的信息时,如果其dad或mom节点不为-1,就将其dad或mom节点的sex赋值,在下面判断同性结婚时起作用。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000;
struct node{
char sex;
int fid,mid;
node():fid(-1),mid(-1),sex('M'){}
}p[maxn];
bool dfs(int a,int b,int depth){
if(a==-1||b==-1) return true;
if(depth>=5) return true;
if((p[a].fid!=-1&&p[a].fid==p[b].fid)||(p[b].mid!=-1&&p[a].mid==p[b].mid)) return false;
return dfs(p[a].fid,p[b].fid,depth+1)&&dfs(p[a].fid,p[b].mid,depth+1)&&dfs(p[a].mid,p[b].fid,depth+1)&&dfs(p[a].mid,p[b].mid,depth+1);
}
int main(){
// freopen("1.txt","r",stdin);
int n,id,k,a,b;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d%*c",&id);
scanf("%c%d%d",&p[id].sex,&p[id].fid,&p[id].mid);
if(p[id].fid!=-1) p[p[id].fid].sex='M';
if(p[id].mid!=-1) p[p[id].mid].sex='F';
}
scanf("%d",&k);
for(int i=0;i<k;i++){
scanf("%d%d",&a,&b);
if(p[a].sex==p[b].sex) printf("Never Mind\n");
else
puts(dfs(a,b,1)?"Yes":"No");
}
return 0;
}
从叶子节点开始遍历,判断两棵子树指定迭代深度内是否有相同节点
#include<iostream>
#include<map>
#include<string>
using namespace std;
struct Person{
char sex;
string father;
};
map<string,Person>people;
bool judge(string a,string b){
int i=1;
for(string A=a;!A.empty();A=people[A].father,i++){
int j=1;
for(string B=b;!B.empty();B=people[B].father,j++){
if(i>=5&&j>=5) return true;
if(A==B&&(i<5||j<5)) return false;
}
}
return true;
}
int main(){
//freopen("1.txt","r",stdin);
ios::sync_with_stdio(false);
int n,m;
cin>>n;
string str,a,b;
while(n--){
cin>>a>>b;
if(b.back()=='n'){
people[a]={'m',b.substr(0,b.size()-4)};
}
else if(b.back()=='r'){
people[a]={'f',b.substr(0,b.size()-7)};
}
else{
people[a].sex=b.back();
}
}
cin>>m;
while(m--){
cin>>a>>str>>b>>str;
if(people.find(a)==people.end()||people.find(b)==people.end()){
cout<<"NA"<<endl;
}
else if(people[a].sex==people[b].sex){
cout<<"Whatever"<<endl;
}
else{
cout<<(judge(a,b)?"Yes":"No")<<endl;
}
}
return 0;
}