n元树的公共祖先节点(C++)第十八届浙大城市学院程序设计竞赛D
链接:https://ac.nowcoder.com/acm/contest/12986/D
来源:牛客网
题目描述
The N-ary tree is a tree that each node has exactly n_child nodes.
You are given an N-ary tree with infinite nodes, each node is numbered from 1 to infinity according to the level order(from left to right, level by level).
Given the number x and y of the two nodes, you have to calculate the lowest common ancestors(LCA) of these two nodes.Definition of the lowest common ancestors(LCA): The LCA of two nodes on the tree refers to the node is the ancestor of these two nodes with the shortest distance to these two nodes, it should be noted that the node itself is also considered its own ancestor. For example, on the 3-ary tree the LCA of node 6 and node 3 is node 1.
#include<iostream>
using namespace std;
int an(int x,int y,int n){
if(x==y)return x;
if(n==1)return x<y?x:y;
else{
while(x!=y){
if(x>y){
if(x%n>1)x=x/n+1;
else x=x/n;
}
if(y>x){
if(y%n>1)y=y/n+1;
else y=y/n;
}
}
return x;
}
}
int main(){
int t;
cin>>t;
while(t--){
int n,x,y;
cin>>n>>x>>y;
cout<<an(x,y,n)<<endl;
}
return 0;
}
此题建议画画图不难发现规律。