完全二叉树从1开始编号,可以利用父结点和子节点的下标关系,通过递归来统计m所在的子树(左子树根节点编号为2*m,右子树为2*m+1)中所有编号小于n的结点个数即可。
#include<stdio.h>
using namespace std;
int fun(int m, int n) {
if (m > n)return 0;
else return fun(m * 2, n) + fun(m * 2 + 1,n) + 1;
}
int main() {
int m, n;
while (scanf("%d %d\n", &m, &n) != EOF) {
if (m == n && n == 0)return 0;
printf("%d\n",fun(m, n));
}
return 0;
}

京公网安备 11010502036488号