当前位置:网站首页>完全二叉树问题
完全二叉树问题
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));
}
}
}
七 测试
绿色为输入,白色为输出
边栏推荐
- 21天打卡挑战学习MySQL——《Window下安装MySql》第一周 第三篇
- 云计算国内外发展现状
- L2-029 特立独行的幸福
- utils timer
- Internet user account information management regulations come into effect today: must crack down on account trading and gray products
- 互联网用户账号信息管理规定今起施行:必须严打账号买卖灰产
- Quickly build a website with static files
- for loop exercises
- pikachu Over permission
- 获国际权威认可 | 云扩科技入选《RPA全球市场格局报告,Q3 2022》
猜你喜欢
云平台建设解决方案
关于IDO预售系统开发技术讲解丨浅谈IDO预售合约系统开发原理分析
Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself
生成器版和查看器版有什么区别?
MiniAPI of .NET6 (14): Cross-domain CORS (Part 1)
嵌入式系统:概述
Canvas App中点击图标生成PDF并保存到Dataverse中
Zilliz 2023 秋季校园招聘正式启动!
First domestic open source framework 】 【 general cloud computing framework, any program can be made into cloud computing.
随机推荐
HDU 5655 CA Loves Stick
Boss: There are too many systems in the company, can you realize account interoperability?
什么是memoization,它有什么用?
pikachu Over permission
[N1CTF 2018] eating_cms
云平台建设解决方案
[MySQL Advanced] Creation and Management of Databases and Tables
Golang Chapter 1: Getting Started
Flutter 桌面探索 | 自定义可拖拽导航栏
Go开发工具GoLand V2022.2 来了——Go 工作区重大升级
21天打卡挑战学习MySQL——《MySQL工具的使用》第一周 第二篇
亿流量大考(2):开发一套高容错分布式系统
2022-08-03 Oracle executes slow SQL-Q17 comparison
Makefile
物联网新零售模式,引领购物新潮流
LabVIEW代码生成错误 61056
log4j-slf4j-impl cannot be present with log4j-to-slf4j
Network basic learning series four (network layer, data link layer and some other important protocols or technologies)
What is memoization and what is it good for?
With 4 years of work experience, the 5 communication methods between multi-threads can't be said, can you believe it?