LCA On N-ary Tree题解
作者:互联网
浙大城院的训练赛前4道是水题,40min可以直接砍掉。接着LCA这道题其实上一次ICPC里出现过,是一道模拟题。现在采用队友的代码学习一下
题目
链接: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).
The first 13 nodes on the 3-ary tree.
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.
输入
4
1 2 3
2 4 6
3 6 3
10000 10000 10000
输出
2
1
1
10000
AC代码
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define pre(i,a,b) for(int i=a;i>=b;--i)
#define m(x) memset(x,0,sizeof x)
const double PI = acos(-1);
const int maxn = 1e6+5;
int a[1005], b[1005];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,x,y,xf;
scanf("%d%d%d",&n,&x,&y);
//特判
if(n==1)
{
printf("%d\n",min(x,y));
continue;
}
if(x==y)
{
printf("%d\n",x);
continue;
}
//xf标记大数初始化,y标记小数
int t=max(x,y);
y=min(x,y);
x=t;
xf = x;
while(xf>=y)
{
if(x%n>1)xf=x/n+1;
else xf=x/n;//根据上文提供构建下层逻辑 求父节点
if(xf<=y)break;
x=xf;
}
//表示xf的父节点恰好是y
if(xf==y)
{
printf("%d\n",xf);
continue;
}
//在此只能保证x在y的下层或是同层 故逆序递推时应先更新x
while(x!=y)
{
if(x%n>1)x=x/n+1;
else x=x/n;
if(x==y)break;
if(y%n>1)y=y/n+1;
else y=y/n;
}
printf("%d\n",x);
}
return 0;
}
思想
这道题首先最重要的是建树,题目规定了是n进制数,我们来模拟几个图。
我们可以发现以下几个规律:
1.一进制树很显然是特判,x和y的LCA很显然是min{x,y};
2.我们可以找到一条中间枝,上面的值很显然是n^a(a表示层数,1所在的位置是0层)
3.每层的个数是n^a,那么a层的起始数可以通过推断得从2层开始,为
求上层节点的模块
while(xf>=y)
{
if(x%n>1)xf=x/n+1;
else xf=x/n;//根据上文提供构建下层逻辑 求父节点
if(xf<=y)break;
x=xf;
}
//在此只能保证x在y的下层或是同层 故逆序递推时应先更新x
while(x!=y)
{
if(x%n>1)x=x/n+1;
else x=x/n;
if(x==y)break;
if(y%n>1)y=y/n+1;
else y=y/n;
}
标签:node,xf,int,题解,LCA,Tree,tree,ary,nodes 来源: https://blog.csdn.net/DAVID3A/article/details/115176967