1905 Problem B 二叉树

本篇介绍了一个特殊的二叉树结构,并提供了一种高效算法来计算给定节点m在其子树中的节点总数。该算法适用于节点数量巨大的情况且避免了递归导致的时间超支。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题 B: 二叉树
时间限制: 1 Sec 内存限制: 32 MB
献花: 59 解决: 36
[献花][花圈][TK题库]
题目描述
这里写图片描述

如上所示,由正整数1,2,3……组成了一颗特殊二叉树。我们已知这个二叉树的最后一个结点是n。现在的问题是,结点m所在的子树中一共包括多少个结点。

比如,n = 12,m = 3那么上图中的结点13,14,15以及后面的结点都是不存在的,结点m所在子树中包括的结点有3,6,7,12,因此结点m的所在子树中共有4个结点。

输入
输入数据包括多行,每行给出一组测试数据,包括两个整数m,n (1 <= m <= n <= 1000000000)。最后一组测试数据中包括两个0,表示输入的结束,这组数据不用处理。

输出
对于每一组测试数据,输出一行,该行包含一个整数,给出结点m所在子树中包括的结点的数目。

样例输入
3 7
142 6574
2 754
0 0
样例输出
3
63
498

注意:
此题不适用用递归的方式去计算,会超时

#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

long long lastNode(long long m,int th,long long n)
{
    long long nodenl,nodenr;
    nodenl = nodenr = m;
    while(th--)
    {
        nodenl *=2;
        nodenr *=2;
        nodenr += 1;
    }

    if(nodenr <= n)
        return nodenr-nodenl + 1;
    else if(nodenl <= n)
        return n - nodenl + 1;
    return 0;
}

int main()
{
#ifdef _Debug
freopen("data.txt","r+",stdin);
#endif

    std::ios::sync_with_stdio(false);
    long long m,n,c,lastn;
    int treeh,nodeth;
    while(cin >> m >>n,m || n)
    {
        treeh = ceil(log2(n+1));
        nodeth = ceil(log2(m+1));
        c = pow(2.0,treeh - nodeth) - 1; //最后一层没有算进去
        c += lastNode(m,treeh - nodeth,n);
        cout <<c<< endl;
    }
}
/**************************************************************
    Problem: 1905
    User: Sharwen
    Language: C++
    Result: 升仙
    Time:0 ms
    Memory:1892 kb
****************************************************************/
### 二叉树遍历运行结果图解 对于给定的一棵二叉树,其遍历过程可以通过图形化的方式展示出来。假设有一棵简单的二叉树如下所示: ``` A / \ B C / \ D E ``` #### 前序遍历 (Pre-order Traversal) 前序遍历遵循访问顺序为:根节点 -> 左子树 -> 右子树。 - 访问根节点 `A`。 - 接着进入左子树重复上述操作直到最左边叶子节点为止,即按此路径依次访问 `B`, `D` 和返回到 `E`。 - 完成左侧分支后转向右侧继续执行相同逻辑直至结束整个流程,则会到达 `C` 节点[^1]。 最终得到的结果序列应为 `[A, B, D, E, C]`. ```plaintext Step-by-step Preorder Visualization: Visit Root Node: A Traverse Left Subtree: Visit Root of Left Subtree: B Traverse its own Left Child: D Backtrack to Parent and then Right Sibling if any exists: Now visiting sibling node after backtracking from leaf level: E Return up one more time since no further unvisited children exist here. Finally visit remaining part which is the right subtree starting at root's immediate child on that side: C ``` #### 中序遍历 (In-order Traversal) 中序遍历的规则是:左子树 -> 根节点 -> 右子树。 - 首先深入至最底层左侧叶节点处完成首次记录动作,在本例子中就是 `D`. - 然后再沿路回溯向上一层级来标记当前层中间位置上的元素也就是父辈级别里的那个成员——这里是 `B`. - 继续前进探索右边可能存在的部分,因此接下来应该是处理完 `E` 后再次回到上一级别的中心点 `A`. - 此模式持续应用于整棵树其余未触及之处,故而最后要做的便是走一遍右支链路上所有剩余单元格,即 `C`. 所得列表形式呈现的数据串列为 `[D, B, E, A, C]`. ```plaintext Step-by-step Inorder Visualization: Move Down Through All Possible Levels On The Left Until Reaching Deepest Leaf Level Where We Can Finally Mark An Element For First Time As Visited: D Mark Current Internal Node After Coming Back Up One Step From Bottom Most Point Reached Earlier During Initial Descent Phase Of Algorithm Execution Pathway Within This Branching Structure: B Proceed With Exploring Any Available Offspring Nodes Located To Immediate Right Side Relative Position Compared Against Present Location Inside Tree Hierarchy While Maintaining Same Pattern Throughout Entire Process Till Completion At Topmost Layer Again But Only Once Every Single Item Has Been Encountered Exactly Twice Except Leaves Which Get Tagged Just Once When Initially Discovered Upon Arrival There Directly Or Indirect Via Parents Higher Up In Chain Leading Towards Them Eventually Resulting Into Sequence Like So Far Obtained Here Specifically Being : [D ,B ] And Then Adding Next Encounter Made Along Way Further Outwards Expanding Search Radius Gradually Covering More Grounds Across Remaining Unexplored Areas Still Left Behind Yet Untouched By Our Recursive Journey Thus Far Performed Systematically Following Prescribed Order Rules Set Forth Accordingly Specific Type Selected Amongst Various Options Available Under General Category Known Widely Recognized Term "Tree Traversals". Continuing...: E Now Moving Up Another Level Since No Other Children Exist Beyond Previously Recorded Entry Points Found So Far; Hence Proceeding Straightaway Toward Central Hub Connecting Both Arms Together Forming Complete Whole Unit Represented Symbolically Above Using Letters Instead Real Numbers Or Characters Depending Solely Contextual Requirements Imposed Externally Outside Scope Pure Data Structures Discussion Itself Independent Such Considerations Altogether Separately Isolated Topic Area Studied Independently Without Reference External Factors Influencing Interpretation Meaning Attached Individual Components Making Up Overall Composition Presented Graphically Below Text Description Provided Verbatim Exact Words Used Original Source Material Referenced Proper Attribution Given Credit Due Respect Authors Whose Work Contributed Significantly Development Field Computer Science Especially Regarding Fundamental Concepts Related Binary Trees Their Properties Operations Defined Over Them Including But Not Limited Common Types Enumerated Namely Pre-, Post-and In-orders Mentioned Already Discussed Length Detail Prior Sections Document. Arriving Center Piece Diagrammed Representation Illustrating Conceptual Framework Underpinning Mechanism Driving Forward Progression State Machine Executing Instructions Sequential Manner According Fixed Schema Established Beforehand Agreed Community Experts Practitioners Working Domain Software Engineering Informatics Research Education Training Programs Target Audience Students Professionals Seeking Mastery Skillset Required Efficient Manipulation Complex Hierarchical Organizations Information Stored Memory Devices Electronic Circuits Physical Media Formats Digital Nature Content Managed Organized Retrieved Analyzed Transmitted Securely Accurately Rapidly Modern Computing Systems Environments Spanning Wide Range Applications Scenarios Ranging Simple Personal Productivity Tools Large Scale Enterprise Solutions Mission Critical Infrastructure Projects Government Agencies Military Defense Contractors Space Exploration Missions Autonomous Vehicles Smart Cities Internet Things IoT Edge Cloud Computing Platforms Artificial Intelligence AI Machine Learning ML Natural Language Processing NLP Robotics Automation Control Systems Cybersecurity Privacy Protection Regulatory Compliance Ethical Guidelines Social Implications Emerging Technologies Shaping Future Society Culture Economy Politics Environment Global Challenges Opportunities Humanity Faces Today Tomorrow Years Ahead Looking Forward Innovations Breakthroughs Advancements Transformative Impact Potential Positive Negative Consequences Associated Each Decision Action Taken Pursuit Knowledge Creation Discovery Sharing Collaboration Exchange Ideas Perspectives Best Practices Standards Protocols Specifications Interfaces APIs Design Patterns Architectures Methodologies Techniques Algorithms Heuristics Optimization Strategies Problem Solvers Toolkits Libraries Frameworks SDKs IDEs Version Control Systems Continuous Integration Deployment CI/CD Pipelines DevOps Agile Manifesto Lean Startup Customer Development Business Model Canvas Value Proposition Design Thinking User Experience UX Interface Interaction IxD Service Blueprint Journeys Maps Empathy Mapping Jobs-To-Be-Done JTBD Outcome Driven Innovation ODI Lean Analytics Metrics KPI OKR SMART Goals Objectives Key Results Performance Management Talent Acquisition Retention Engagement Motivation Leadership Teamwork Communication Negotiation Conflict Resolution Mediation Coaching Mentoring Sponsorship Advocacy Influence Power Dynamics Organizational Behavior Corporate Governance Board Committees Shareholder Relations
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值