题解:P13098 构造大师贝贝

· · 题解

思路

诈骗题目,一不留神就会去想质因数分解做法,然后就做烦了,还不知道到底能不能做出来。

显然,对于任何一个数 x,\text{lowbit}(x) 一定是它的因数(不知道 \text{lowbit}(x) 是什么的左转树状数组),所以可以不断加上 \text{lowbit}(x),最后 x 一定能变成 2^{2m} 即 2^{m^2},这是个完全平方数,然后就做完了。

易得增加次数不超过 O(\log n),不到 50,完全可行,增加后判断是否为完全平方数即可。

代码实现

#include<bits/stdc++.h>
#define int long long
using namespace std;
int lowbit(int u){return u&-u;}
int x[105];
signed main(){
    int T;
    scanf("%lld",&T);
    while(T--){
        int n,top=0;
        scanf("%lld",&n);
        for(int i=1;;i++){
            if((int)(sqrt(n))*(int)(sqrt(n))==n)break;
            x[++top]=lowbit(n);
            n+=lowbit(n);
        }
        printf("%lld\n",top);
        if(top){
            for(int i=1;i<=top;i++)printf("%lld ",x[i]);
            printf("\n");
        }
    }
    return 0;
}