[DFS] [洛谷] P1010 幂次方

简单水题

题解都省的看

想到用数组保留二进制以后

XJB递归一下就完了

注:

再提示自己一遍

所有的递归题

不要上来就去搞递归 剪枝 终止条件

应该把第一层的内容(大框架)全部搞出来

然后向下递归即可

以本题为例

能让程序输出

137 = 2(7)+2(3)+2(0)2(7)+2(3)+2(0)

就已经解决了

剩下的就是细枝末节简单的东西了

#include <iostream>
using namespace std;

typedef long long ll;


const ll MAXN = 1e2 + 10;

string ans = "";

void dfs(ll x)
{
    ll arr[MAXN] = {0};
    ll tf = 0;

    while(x)
    {
        arr[tf++] = x % 2;
        x /= 2;
    }

    bool flag = true;
    
    for(int i = tf; i >= 0; i--)
    {
        if(arr[i] == 1)
        {
            if(flag)
            {
                if(i == 1)
                {
                    ans = ans + "2";
                }
                else if(i == 0)
                {
                    ans = ans + "2(0)";
                }
                else
                {
                    ans = ans + "2(";
                    
                    dfs(i);
                    
                    ans = ans + ')';
                }
                    
                flag = false;
            }
            else
            {
                if(i == 1)
                {
                    ans = ans + "+2";
                }
                else if(i == 0)
                {
                    ans = ans + "+2(0)";
                }
                else
                {

                    ans = ans + "+2(";
                    dfs(i);
                    ans = ans + ')';
                }
            }
        }
    }
}

int main()
{
    ll a;

    cin>>a;

    dfs(a);

    cout<<ans<<endl;

    return 0;
}

 

posted @ 2018-08-03 10:33  张浦  阅读(89)  评论(0编辑  收藏  举报