【题目链接】Neko Performs Cat Furrier Transform
【题目分析】要求将一个数字变成2n-1,通过尝试我们发现如果将最低位的全零位和对应的全一数字(例如11000对应的就是111)异或那么数字就会变成想要的结果(11111)
但是如果前面还有0(比如110100)那么过程应该如下:110100^000011变成110111加一后变成111000然后就会得到结果,总之我们需要做的就是不断将末尾的全零变成全1,然后在加一的时候就会进位将前面的0消灭
为了检验是否已经得到结果,我们不妨预处理一个所有结果的数组,然后在数组中用lower_bound和upper_bound找
尾部的全零位的查找可以借鉴树状数组中最低位1lowbit(x)=x&(-x),最低位1后面全都是0,因此全零对应的的全一数字为lowbit(x)-1
#include<cstdio>
#include<algorithm>
using namespace std;
int s[50];
int cnt=0;
int check[30];
bool find(int x)
{
//printf("test : lower_bound(check,check+30,x)-check=%d\n",lower_bound(check,check+30,x)-check);
//printf("test : upper_bound(check,check+30,x)-check=%d\n",upper_bound(check,check+30,x)-check);
if(lower_bound(check,check+30,x)-check==upper_bound(check,check+30,x)-check)
return false;
else
return true;
}
int work(int x)
{
return (x&(-x))-1;
}
int main()
{
for(int i=0;i<30;i++)
{
check[i]=(1<<i)-1;
}
int x,y,ans=0;
scanf("%d",&x);
while(ans<40)
{
//printf("test x=%d\n",x);
y=work(x);
//printf("test y=%d\n",y);
s[cnt++]=lower_bound(check,check+30,y)-check;
x=x^y;
//printf("test x=%d\n",x);
ans++;
if(!find(x))
{
//printf("test x=%d\n",x);
x++;
ans++;
}
else
{
break;
}
}
printf("%d\n",ans);
for(int i=0;i<cnt;i++)
{
printf("%d ",s[i]);
}
return 0;
}