二叉排序树(Binary Sort Tree)又称二叉查找树(Binary Search Tree),亦称二叉搜索树。 它或者是一棵空树;或者是具有下列性质的二叉树: (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值; (2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值; (3)左、右子树也分别为二叉排序树;
朴素想法代码TLE(利用二叉树来模拟)
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;
const int N = 20;
int D,I;
int tree[1 << N];
int main(){
int cas;
scanf("%d",&cas);
while(scanf("%d%d",&D, &I) == 2){
memset(tree, 0, sizeof(tree));
int n = (1 << D) - 1, k;
for(int i=0; i<I; i++){
k = 1;
for(;;){
tree[k] = !tree[k];
k = tree[k] ? (k << 1) : (k << 1 | 1);
if(k > n) break;
}
}
printf("%d\n",k/2);
}
return 0;
}
找规律AC
当I是奇数,它是向左走的第(1+I)/2个小球;当I是偶数,他是向右走的第I/2个小球。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;
const int N = 20;
int D,I;
int tree[1 << N];
int main(){
int cas;
scanf("%d",&cas);
while(scanf("%d%d",&D, &I) == 2){
int k = 1;
for(int i = 0; i < D - 1; i++){
if(I & 1){
k = k << 1;
I = (1 + I) / 2;
}
else{
k = k << 1 | 1;
I = I / 2;
}
}
printf("%d\n",k);
}
return 0;
}