二叉树——UVA679

用二叉树来模拟的算法会TLE,只能找规律来过
画图会发现,当I为奇数时,都会掉到左子树去,偶数则右。然后判断一下何时到叶子节点就可以了

TLE的算法

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define N 1048577

int main(){
    //freopen("in.txt","r",stdin);
    int n,x,y,li ;
    int a[N];
    scanf("%d",&n);
    while(~scanf("%d",&x)){
        int k;
        li = (1<<x) -1;
        if(x == -1) break;
        scanf("%d",&y);
        for(int j = 1;j <= li;j++)
            a[j] = 0;
        for(int j = 1;j <= y;j++){
            for(k = 1;2*k <= li;){
                a[k] = !a[k];
                k = a[k]==0?(2*k+1):(2*k);
            }
        }
        printf("%d\n",k);
    }
    return 0;
}

AC

#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

int main(){
    //freopen("in.txt","r",stdin);
    int n,D,I;
    scanf("%d",&n);
    while(~scanf("%d",&D)){
        int k = 1;
        if(D== -1) break;
        long long li = (1<<D)-1;
        scanf("%d",&I);
        for(k = 1;k <=li;){
            if(I%2){
                I=I/2+1;
                k*=2;
            }
            else{
                I=I/2;
                k=2*k+1;
            }
        }
        printf("%d\n",k/2);
    }
    return 0;
}
posted @ 2015-11-22 16:45  sean10  阅读(215)  评论(0编辑  收藏  举报