当前位置:网站首页>完全二叉树问题
完全二叉树问题
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));
}
}
}七 测试
绿色为输入,白色为输出

边栏推荐
- 封装、包、访问权限修饰符、static变量
- With 4 years of work experience, the 5 communication methods between multi-threads can't be said, can you believe it?
- [MySQL Advanced] Creation and Management of Databases and Tables
- 授人以渔 - 如何自行查询任意 SAP UI5 控件属性的文档和技术实现细节试读版
- 2022-08-02 mysql/stonedb slow SQL-Q18 - memory usage surge analysis
- Conditional Statements for Shell Programming
- 伴随着元宇宙、web3.0等概念的兴起,数字人、数字场景等诸多数字化的形态开始出现
- UVa 10003 - Cutting Sticks(白书,区间DP)
- The development status of cloud computing at home and abroad
- 亿流量大考(2):开发一套高容错分布式系统
猜你喜欢
随机推荐
21天打卡挑战学习MySQL—Day第一周 第一篇
斩获双奖|易知微荣获“2021中国数字孪生解决方案优秀供应商”“中国智能制造优秀推荐产品”双奖项!
4年工作经验,多线程间的5种通信方式都说不出来,你敢信?
How to write a database document management tool based on WPF (2)
授人以渔 - 如何自行查询任意 SAP UI5 控件属性的文档和技术实现细节试读版
Embedded Systems: GPIO
Adobe是什么?
for loop exercises
Websocket multi-threaded sending message error TEXT_PARTIAL_WRITING--Use case of spin lock replacing synchronized exclusive lock
.NET6之MiniAPI(十四):跨域CORS(上)
Codeup brushing notes - simple simulation
互联网用户账号信息管理规定今起施行:必须严打账号买卖灰产
Internet user account information management regulations come into effect today: must crack down on account trading and gray products
如何基于WPF写一款数据库文档管理工具(二)
2019年10月SQL注入的两倍
PowerMockup 4.3.4::::Crack
113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself
[MySQL Advanced] Creation and Management of Databases and Tables
node连接mysql数据库报错:Client does not support authentication protocol requested by server
UVa 1025 - A Spy in the Metro (White Book)









