当前位置: 首页 > article >正文

小R的二叉树探险 | 模拟

问题描述

在一个神奇的二叉树中,结构非常独特:

每层的节点值赋值方向是交替的,第一层从左到右,第二层从右到左,以此类推,且该二叉树有无穷多层。
小R对这个二叉树充满了好奇,她想知道,在二叉树中两个节点之间x, y的路径长度是多少。

graph TD
  1((1));2((2));3((3));4((4));
  5((5));6((6));7((7));8((8));
  9((9));10((10));11((11));
  1---3;1---2;3---4;3---5;
  2---6;2---7;6---11;6---10;
  7---9;7---8;

测试样例

示例 1:

输入:x = 11, y = 4
输出:5

示例 1:

输入:x = 2, y = 5
输出:3

示例 1:

输入:x = 7, y = 7
输出:0

题解:

        因为每层的个数都是上一层乘二,同时是2^{n}个,n为层数。所以\log _{2}n就是x,y所在的层数。接着通过层高的奇偶性判断排列的顺序,再与x,y相减便可得到所在的位置。最后一层一层向上找相同的根即可得到路程。

代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#include <functional>
using namespace std;
typedef long long int ll;

int countplace(int dx,int x){
    int i,cnt=0;
    if(dx%2==1){
        return pow(2,dx)-(x-pow(2,dx));
    }
    else{
        return x-pow(2,dx)+1;
    }
}

int solution(int x, int y) {
    // write code here
    if(x<y){
        int tt=x;
        x=y;y=tt;
    }
    int i,j,k,t=max(x,y),maxi=0;
    int dx=0,dy=0,px=0,py=0,lx=0,ly=0;
    dx=log2(x);dy=log2(y);
    cout << dx << " " << dy << "\n";
    px=countplace(dx,x);
    py=countplace(dy,y);
    /*
    if(dx==dy){
        return abs(px-py);
    }
    */
    while(dx!=dy){
        if(px%2!=0){
            px++;
        }
        px/=2;dx-=1;lx++;
    }
    while(px!=py){
        if(px%2!=0){
            px++;
        }
        if(py%2!=0){
            py++;
        }
        px/=2;dx-=1;lx++;
        py/=2;dy-=1;ly++;
    }
    //cout << lx+ly << "\n";
    return lx+ly;
}

int main() {
    std::cout << (solution(11, 4) == 5) << std::endl;
    std::cout << (solution(2, 5) == 3) << std::endl;
    std::cout << (solution(7, 7) == 0) << std::endl;
    std::cout << (solution(383786261, 653995378)==57) << std::endl;
    std::cout << (solution(997295150, 889335947)==56) << std::endl;
    return 0;
}


http://www.kler.cn/a/413686.html

相关文章:

  • Windows 11 搭建 Docker 桌面版详细教程
  • 读书笔记_《创华为.任正非传》_精华书摘
  • 241125学习日志——[CSDIY] [ByteDance] 后端训练营 [16]
  • 【通俗理解】Adaptive Gradient Algorithm(自适应梯度算法)——从梯度下降到优化器选择
  • 《Gin 框架中的表单处理与数据绑定》
  • 跳表(Skip List)
  • TCP网络套接字
  • Python中3中并发对比
  • 【从零开始的LeetCode-算法】3202. 找出有效子序列的最大长度 II
  • 整合Springboot shiro jpa mysql 实现权限管理系统(附源码地址)
  • Reachy 2,专为AI与机器人实验室打造的卓越开源双臂移动操作平台!
  • 【计网】自定义协议与序列化(一) —— Socket封装于服务器端改写
  • 数据库死锁排查案例
  • 设计模式——MVC模式
  • 鉴于很多笔记本笔记不安全,手机下载安全开源笔记本的方法
  • 接口的扩展
  • go web单体项目 学习总结
  • 性能测试工具|如何有效度量前端性能
  • idea或datagrip连接opengauss数据库
  • SQL for JSON