卡码网-11.共同祖先

11. 共同祖先

题目描述

小明发现和小宇有共同祖先!现在小明想知道小宇是他的长辈,晚辈,还是兄弟。

输入描述

输入包含多组测试数据。每组首先输入一个整数N(N<=10),接下来N行,每行输入两个整数a和b,表示a的父亲是b(1<=a,b<=20)。小明的编号为1,小宇的编号为2。
输入数据保证每个人只有一个父亲。

输出描述

对于每组输入,如果小宇是小明的晚辈,则输出“You are my younger”,如果小宇是小明的长辈,则输出“You are my elder”,如果是同辈则输出“You are my brother”。

输入示例
5
1 3
2 4
3 5
4 6
5 6
6
1 3
2 4
3 5
4 6
5 7
6 7
输出示例
You are my elder
You are my brother

import java.util.Scanner;

public class Main{
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //使用一个数组进行数字祖先的映射 arr[i]=j  i的祖先为j
        int[] arr = new int[21];
        
        while (sc.hasNext()){
            int n = sc.nextInt();
            while (n > 0){
                n--;
                int child = sc.nextInt();
                int parent = sc.nextInt();
                arr[child] = parent;
            }
            int a = arr[1];//第一个
            int b = arr[2];
            //分别找a和b的祖先,每次往后面找一个
            while (a != 0 && b != 0){
                a = arr[a];
                b = arr[b];
            }

            //找到至少一个的祖宗,先找到的那个为小的
            if (a == 0 && b ==0){
                System.out.println("You are my brother");
            }else if (b == 0) {
                System.out.println("You are my elder");
            }else {
                System.out.println("You are my younger");
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值