当前位置:网站首页>完全二叉树问题
完全二叉树问题
2022-08-03 22:41:00 【chengqiuming】
一 原问题描述
BST - POJ 2309 - Virtual Judgehttps://vjudge.net/problem/POJ-2309
二 输入和输出
1 输入
第 1 行包含一个整数 N,表示查询的数量。在接下来的 N 行中,每行都包含一个数字,表示根号为 X 的子树。
2 输出
共 N 行,其中第 i 行包含第 i 个查询的答案。
三 输入和输出样例
1 输入样例
2
8
10
2 输出样例
1 15
9 11
四 分析
本问题规律可循,若 n 是奇数,那么必然是叶子节点,最大数和最小数都是它自己。否则求 n 所在的层次(倒数的层数,底层为 0),它的层数就是 n 的二进制表示中从低位开始第1个1所在的位置 i(最后一个非0位),例如 6 的二级制为110,从低位开始第1个1的位置是1,因此 6在第1层;12的二进制是1100,从低位开始第1个1的位置是2,因此12在第2层,如下图所示。

i 的值即为层数,可得到 n 的左右子树各有 k = 2^i-1个节点,那么最小数是 n-k,最大数是n+k,那么怎么求 2^i呢?
实际上,想得到最后一个非 0 位,只需先将原数取反后加1,此时除了最后一个非 0 位,其他位均与原数相反,直接与原数按位与运算即可得到最后一个非0位。
五 算法设计
1 求解logbit(n)=n&(-n)。
2 让 看= lowbit(n)-1,输出最小数 n-k,最大数 n+k。
六 代码
package poj2309;
import java.util.Scanner;
public class Poj2309 {
static int lowbit(int n) {
return n & (-n);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T, n, k;
T = scanner.nextInt();
while (T-- > 0) {
n = scanner.nextInt();
k = lowbit(n) - 1;
System.out.println((n - k) + " " + (n + k));
}
}
}七 测试
绿色为输入,白色为输出

边栏推荐
猜你喜欢

for loop exercises

Teach a Man How to Fish - How to Query the Properties of Any SAP UI5 Control by Yourself Documentation and Technical Implementation Details Demo
![[b01lers2020]Life on Mars](/img/d0/d5c9b7224542c8843ce29adc7ef713.png)
[b01lers2020]Life on Mars

Boss: There are too many systems in the company, can you realize account interoperability?

物联网新零售模式,引领购物新潮流

113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself

投资性大于游戏性 NFT游戏到底是不是门好生意

Live Preview | Build Business Intelligence, Quickly Embrace Financial Digital Transformation

趣链的产品构架

Quickly build a website with static files
随机推荐
Websocket multi-threaded sending message error TEXT_PARTIAL_WRITING--Use case of spin lock replacing synchronized exclusive lock
websocket多线程发送消息报错TEXT_PARTIAL_WRITING--自旋锁替换synchronized独占锁的使用案例
What is Adobe?
With the rise of concepts such as metaverse and web3.0, many digital forms such as digital people and digital scenes have begun to appear.
嵌入式系统:GPIO
云平台建设解决方案
Fluorescein-PEG-CLS,胆固醇-聚乙二醇-荧光素科研试剂
2022的七夕,奉上7个精美的表白代码,同时教大家快速改源码自用
utlis thread pool
noip preliminary round
Flutter 桌面探索 | 自定义可拖拽导航栏
On the Qixi Festival of 2022, I will offer 7 exquisite confession codes, and at the same time teach you to quickly change the source code for your own use
Cisco ike2 IPSec configuration
图的基础概念
noip初赛
Shell编程的条件语句
Basic Concepts of Graphs
老板:公司系统太多,能不能实现账号互通?
【MySQL进阶】数据库与表的创建和管理
466. Count The Repetitions