Little A gets to know a new friend, Little B, recently. One day, they realize that they are family 500 years ago. Now, Little A wants to know whether Little B is his elder, younger or brother.
翻译:
小 A 最近认识了一个新朋友小 B。有一天,他们意识到他们是 500 年前的家人。现在,小A想知道小B是他的长辈、弟弟还是弟弟。
There are multiple test cases.
For each test case, the first line has a single integer, n (n<=1000). The next n lines have two integers a and b (1<=a,b<=2000) each, indicating b is the father of a. One person has exactly one father, of course. Little A is numbered 1 and Little B is numbered 2.
Proceed to the end of file.
翻译:
有多个测试用例。
对于每个测试用例,第一行有一个整数 n (n<=1000)。接下来的 n 行各有两个整数 a 和 b (1<=a,b<=2000),表示 b 是 a 的父亲。当然,一个人只有一个父亲。小 A 编号为 1,小 B 编号为 2。
继续到文件末尾。
For each test case, if Little B is Little A’s younger, print “You are my younger”. Otherwise, if Little B is Little A’s elder, print “You are my elder”. Otherwise, print “You are my brother”. The output for each test case occupied exactly one line.
翻译:
对于每个测试用例,如果小 B 比小 A 小,则打印“You are my young”。否则,如果小 B 是小 A 的长辈,则打印“你是我的长辈”。否则,打印“你是我的兄弟”。每个测试用例的输出正好占一行。
样例输入
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
解题思路:
题目其实是层层递进的关系,就是先找到A的父亲,再找到A的父亲的父亲,再找到A的父亲的父亲的父亲,首先先初始一个计数器,从A出发,找到A的父亲的时候计数器加一,并且变量改变,改成找用A的父亲代替原本记录A的值,继续寻找已经替换值的父亲,也就是A的父亲的父亲,当已经遍历整个二维数组(输入的父子关系用列数为2的二维数组记录),也就是已经找不到当前A的值的父亲的时候,A的值就是代表了先祖,这时返回计数器的值,计数器的值代表了先祖跟一开始的A隔了几代,用相同的方法处理B,得到另一个计数器,题目说明A和B是家人,所以应该是存在一个共同的先祖(样例也存在),比较计数器的大小关系就能说明他们之间是长辈,兄弟还是后辈的关系,问题解决。
注意事项:
题目说明A和B的编号,也就是1和2,直接使用
参考代码(java):
import java.util.Scanner;
public class Main {
public static int getsum(int num,int me,int [][]values,int length)
{
for(int i=0;i<length;i++)
{
if(values[i][0]==me)//检测出关系中存在这当前值跟关系中为儿子的值相同
{
me = values[i][1];//把当前值改为关系中为父亲的值,下一步循环找父亲的父亲
num = num + 1;//计数器加一
}
}
return num;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int a = scanner.nextInt();
int res[][]=new int[a][2];
for(int i=0;i<a;i++)
{
res[i][0] = scanner.nextInt();
res[i][1] = scanner.nextInt();
}
int numbera=getsum(0,1,res,a);//得到两个计数器
int numberb=getsum(0,2,res,a);
if(numbera<numberb)//直接进行比较
System.out.println("You are my younger");
else if(numbera==numberb)
System.out.println("You are my brother");
else
System.out.println("You are my elder");
}
}
}
一开始本想用Python写,但是因为超时一直交不上去,猜测是因为语言问题,众所周知Python的运行时间很慢,所以换成java写。同样的思路java交上去了,Python超时。
参考代码(Python):
def getsum(num, me, values, length):
for i in range(length):
if values[i][0] == me: #检测出关系中存在这当前值跟关系中为儿子的值相同
me = values[i][1] #把当前值改为关系中为父亲的值,下一步循环找父亲的父亲
num = num + 1 #计数器加一
return num
while True:
try:
a = int(input())
res = []
for i in range(a):
x, y = map(int, input().strip().split())
b = [x, y]
res.append(b)
numbera = getsum(0, 1, res, a) #得到两个计数器
numberb = getsum(0, 2, res, a)
if numbera < numberb: #直接进行比较
print("You are my younger")
elif numbera == numberb:
print("You are my brother")
else:
print("You are my elder")
except:
break