代码改变世界

2014年山东省第五届ACM大学生程序设计竞赛F题:Full Binary Tree

2015-04-21 21:05  星星之火✨🔥  阅读(237)  评论(0编辑  收藏  举报

题目描述

In computer science, a binary tree is a tree data structure in which each node has at most two children. Consider an infinite full binary tree (each node has two children except the leaf nodes) defined as follows. For a node labelled v its left child will be labelled 2 * v and its right child will be labelled 2 * v + 1. The root is labelled as 1.
 
You are given n queries of the form i, j. For each query, you have to print the length of the shortest path between node labelled i and node labelled j.

输入

First line contains n(1 ≤ n ≤ 10^5), the number of queries. Each query consists of two space separated integers i and j(1 ≤ i, j ≤ 10^9) in one line.

输出

For each query, print the required answer in one line.

示例输入

5
1 2
2 3
4 3
1024 2048
3214567 9998877

示例输出

1
2
3
1
44

分析:对于一颗满的完全二叉树来说,从叶子节点i 到根节点的最短路径长度为logi 向下取整。由于i ≤ 10^9,因此最短路径长度不会超过31,所以树中任意两个节点间的最短路径长度不会超过62。这说明用int 可以存下最多路径长度。至于求这个长度,简单递归(类比于求最大公共祖先)就可以办到:

#include<stdio.h> // 40MS
int count; 
void f(int i, int j);
int main(void)
{
    int n, i, j;
    
    scanf("%d", &n);
    while(n--)
    {
        scanf("%d%d", &i, &j);
        count = 0;
        f(i, j);
        printf("%d\n", count);
    }
}

void f(int i, int j)
{
    if(i == j)
        return;
    count++;
    if(i > j)
        return f(i/2, j);
    else
        return f(i, j/2);
        
}