码迷,mamicode.com
首页 > 其他好文 > 详细

L2-016. 愿天下有情人都是失散多年的兄妹

时间:2017-10-03 15:54:25      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:body   int   for   mat   blog   names   and   main   eve   

采用树存储父亲和母亲信息,共有两个数组,一个用来存储父亲节点信息,一个用来存储母亲

查找函数:向上查找,出了五服或未出五服但可供查找的信息已经完结都要返回yes

                五服之内有相同的祖先返回No

                某些人的父母可能会离婚然后又结婚,需要记录父母的性别

 

#include <stdio.h>
#include <iostream>
#include <memory.h>

using namespace std;
int mother[100000], father[100000];

typedef struct
{
    char sex;
    int fa;
    int mo;
} Man;

Man man[100000];

bool find(int a, int b, int num)
{
    if(a==-1||b==-1)  //our judgement didn‘t arrived great great grandfather, but the record is over, so we can‘t make sure the two is brother and sister, so we return true;
        return 1;
    if(mother[a]!=-1&&mother[a]==mother[b]||father[a]!=-1&&father[a]==father[b])  //a mother node exites and is not equal to b, father node is the same as a
    {
        return false;
    }
    num++;
    //when the number of recursive layer is five,  our judgement arrived great great grandfather,and the same ancestor have not appeared,so we return true
    if(num>=4)
        return true;
    return (find(mother[a], mother[b], num)&&find(mother[a], father[b], num)&&find(father[a], mother[b], num)&&find(father[a], father[b], num));
}


int main()
{
    memset(mother, -1, sizeof(mother));
    memset(father, -1, sizeof(father));
    int n;
    cin >> n;
    for(int i=0; i<n; i++)
    {
        int a;
        cin >> a;
        cin >> man[a].sex >> man[a].fa >> man[a].mo;
        if(man[a].fa!=-1)
        {
            man[man[a].fa].sex = M;  //we need the sex information of somebody‘s father and mother, because the system may let us determine whether the father‘s generation can marry  
            father[a] = man[a].fa;
        }
        else
        {
            father[a] = man[a].fa;
        }
        if(man[a].mo!=-1)
        {
            man[man[a].mo].sex = F;
            mother[a] = man[a].mo;
        }
        else
        {
            mother[a] = man[a].mo;
        }
    }

    int m;
    cin >> m;
    for(int i=0; i<m; i++)
    {
        int a, b;
        cin >> a >> b;
        if(man[a].sex==man[b].sex)
        {
            cout << "Never Mind" << endl;
        }
        else
        {
            if(find(a, b, 0))
                cout << "Yes" << endl;
            else
                cout << "No" << endl;
        }

    }
}

 

L2-016. 愿天下有情人都是失散多年的兄妹

标签:body   int   for   mat   blog   names   and   main   eve   

原文地址:http://www.cnblogs.com/1915884031A-qqcom/p/7623793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!