P1010 幂次方(分治)

https://www.luogu.com.cn/problem/P1010

刚刚看到这个题时,有点懵,如果说这是个数学题

比如说7,应该先求出7 = 4 + 2 + 1;

即先分解出里面应该有最多的2的个数,然后再往下递推

  1. 算出2的多少次幂最接近给出的n;
  2. 用原来n的数减去2的幂,如果这个数大于2,继续对新的n进行搜索;
  3. 如果幂大于2,对幂进行上述搜索;
  4. 一旦输入函数的数为0(退出)或1(2的0次幂)或2(2的1次幂,这时候1不需要输出),输出;
#include <bits/stdc++.h>
using namespace std;
int n;
void search(int x){
    if(!x)
        return;
    int p = 1,q = 0;
    cout << 2;
    while(x >= p){
        p *= 2;
        q++;
    }
    q--;
    if(!q || q == 2)
        cout << "(" << q << ")";
    if(q >= 3){
        cout << "(";
        search(q);
        cout << ")";
    }
    x -= p / 2;
    if(x){
        cout << "+";
        search(x);
    }

}
int main(){
    ios::sync_with_stdio(0);
    cin >> n;
    search(n);
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/xcfxcf/p/12377500.html
今日推荐