33-题目1113:二叉树

来源:互联网 发布:inventor软件多少钱 编辑:程序博客网 时间:2024/05/21 19:49

http://ac.jobdu.com/problem.php?pid=1113

题目描述:

 


    如上所示,由正整数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 120 0
样例输出:
4

#include<iostream>#include<fstream>#include<string>#include<math.h>using namespace std;int main(){int n, m;//n为总节点数,m为子树的根,求该根上的所有节点数,该树为完全二叉树//ifstream cin("data.txt");while (cin >> m >> n && m != 0 && n != 0){int deep = 0, sum = 0, temp = m;for (deep = 0; temp <= n; deep++)temp *= 2;sum = pow(2, deep - 1) - 1;  //统计除叶子节点外的满二叉树的节点总数int limit = m;for (int i = deep - 1; i > 0; i--)limit = 2 * limit + 1;limit = limit > n ? n : limit;sum += limit - temp / 2 + 1;cout << sum << endl;}system("pause");return 0;}


0 0
原创粉丝点击