HDU3786 找出直系亲属(并查集)

一开始想用暴力求解,想了半天没有思路..

其实用并查集好多了:

#include<stdio.h>
#include<string.h>
int find(int array[],int x,int y)
{
    int k=0,mark=0;
    while(array[x] > 0)
    {
        k++;
        if(array[x]==y){mark=1;break;}
        x=array[x];
    }
    if(mark)
        return k;
    else
        return 0;
}
int main()
{
    int child[27];
    int i,k,j,flag,tmpflag;
    char strchild[10],relation[10];
    while(1)
    {
    scanf("%d%d",&i,&k);
    if(!i&&!k)break;
    scanf("\n");
    for(j=1;j<=26;j++)
        child[j]=0;
    while(i--)
    {
        gets(strchild);
        if(strchild[1] != '-')
        child[strchild[1]-'A'+1] =strchild[0]-'A'+1;
        if(strchild[2] != '-')
        child[strchild[2]-'A'+1] =strchild[0]-'A'+1;
    }

    while(k--)
    {
        gets(relation);
        flag = find(child,relation[0]-'A'+1,relation[1]-'A'+1);
        tmpflag = find(child,relation[1]-'A'+1,relation[0]-'A'+1);
        if(!flag&&!tmpflag)printf("-\n");
        else if(flag&&!tmpflag)
        {
            while(flag>2)
            {
                printf("great-");
                flag--;
            }
            if(flag==2)printf("grandparent\n");
            else if(flag==1)printf("parent\n");
        }
        else if(!flag&&tmpflag)
        {
            while(tmpflag>2)
            {
                printf("great-");
                tmpflag--;
            }
            if(tmpflag==2)printf("grandchild\n");
            else if(tmpflag==1)printf("child\n");
        }
    }
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值