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

TLE的算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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;
}