遍历两棵树中是否有相同的节点

比较两棵树中相同深度是否有相同的节点

说白了这就是一道遍历树的题目,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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值