第十八届浙大城市学院程序设计竞赛 D-LCA On N-ary Tree

题目大意:

The N-ary tree is a tree that each node has exactly nn_{}n​ child nodes.
You are given an N-ary tree with infinite nodes, each node is numbered from 11_{}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

思路:

注意到子节点和父节点有数学关系:father=(son+n-2)/n,由此即可循环求父节点。还有的做法是构建这棵树。这个数学关系是在画树中找到规律,确切的说是假设出来的,试了几个例子都是对的就直接写代码了。

反思:

这题在比赛中没有做,只是看了一眼,因为看到了一个比较熟悉的题目,但又做不出来,就一直被卡了,这题没做出来还有一个原因知道但是没有学过LCA的算法,就确信自己肯定做不出来,其实后来想想这题我也没有用到LCA,只不过是到思维题。所以说比赛以后还是尽量跟着榜走,如果剑走偏锋做不出来就赶紧回来跟榜,而且也不要被知识所限制,没学过可以现场造啊(哈哈)。

代码:

#include<cstdio>
using namespace std;
bool ok=0;
int main()
{
    int t,n;
    scanf("%d",&t);
    int z,x,y;
    for(int i=1;i<=t;i++){
        scanf("%d%d%d",&z,&x,&y); 
        int fa=x,fb=y;
        if(z==1){
            if(fa>fb)printf("%d\n",fb);
            else printf("%d\n",fa);
        }
        else{
            while(1){
                 if(fa==fb){
                     if(fa==0){
                         printf("1\n");
                     }
                     else printf("%d\n",fa);
                     break;
                }
                else if(fa>fb){
                    fa=(fa+z-2)/z;
                }
                else if(fb>fa){
                    fb=(fb+z-2)/z;
                }
             }
        }
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值