- 共同祖先(卡码网)
题目描述
小明发现和小宇有共同祖先!现在小明想知道小宇是他的长辈,晚辈,还是兄弟。
输入
输入包含多组测试数据。每组首先输入一个整数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
题解(C++版本)
#include<bits/stdc++.h>
using namespace std;
int n, fa[25],u, v,h[25];
vector<int> E[25];
bool vis[25],ex[25];
void dfs(int x, int depth){
for(int i = 0; i < E[x].size(); i++){
v = E[x][i];
if(!vis[v]){
vis[v] = 1;
h[v] = depth + 1;
dfs(v, depth + 1);
}
}
}
int main(){
while(~scanf("%d", &n)){
memset(vis, 0, sizeof vis);
memset(ex, 0, sizeof ex); //标记该编号是否存在
for(int i = 1; i <= 20; i++) fa[i] = i, E[i].clear();
for(int i = 1; i <= n; i++){
scanf("%d%d", &u, &v);
ex[u] = ex[v] = 1;
fa[u] = v;
E[v].push_back(u);
}
int root = 0;
for(int i = 1;i <= 20; i++){
//printf("fa[%d] = %d\n", i, fa[i]);
if(ex[i]&&fa[i] == i){
root = i;
break;
}
}
vis[root] = 1;
h[root] = 1;
dfs(root, 1);
//printf("%d %d %d\n",root, h[1], h[2]);
if(h[1] == h[2]) printf("You are my brother\n");
else if(h[1] < h[2]) printf("You are my younger\n");
else printf("You are my elder\n");
}
return 0;
}