n元树的公共祖先节点(C++)第十八届浙大城市学院程序设计竞赛D

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;	
}

此题建议画画图不难发现规律。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值