uva529

题目:
An addition chain for n is an integer sequence <a0,a1,a2,,am> <script type="math/tex" id="MathJax-Element-11"> </script> with the following four properties:
a0 = 1
am = n
a0

#include <iostream>  // 迭代深搜
using namespace std;
#include <stdio.h>
#include <cstring>

int n;
int rec[10000];
int save[10000];
int ans[100];
int deep;
bool flag;
int fsize;
void dfs(int cur,int deep) {
//  printf("%d",n);
/*  if(n == 1) {
        fsize = 1;
        return;
    }
    if(n == 2) {
        fsize = 2;
        return;
    }
    if(n == 4) {
        fsize = 3;
        return;
    }
    if(k == n) {
    //  fsize = size;
        if(size < fsize) {
            fsize = size;
            for(int i = 0 ; i < size; i++) {
                save[i] = rec[i];
            }
        }
        return;
    }
    if(k > n)
        return;
    for(int i = 0 ; i < size; i++) {
        rec[size] = k + rec[i];
        dfs(k +rec[i],size+1);
        rec[size] = 0;
    }*/
    if(cur == deep) {
        if(ans[cur] == n)
            flag = true;
        return;
    }

    for(int  i = 0; i <= cur; i++) 
        for(int j = i; j <= cur; j++) 
            if(ans[i]+ans[j] > ans[cur] && ans[i] + ans[j] <= n) {
                int sum = ans[i] + ans[j];
                for(int k = cur+1; k<= deep; k++)
                    sum = sum *2;
                if(sum  < n)
                    continue;
                ans[cur +1]  = ans[i] +ans[j];
                dfs(cur+1,deep);
                if(flag)
                    return;
            }
}
int main() {

    while(scanf("%d",&n)!=EOF && n){
        ans[0] = 1;
        deep = 0;
        int m = ans[0];
        while(m < n) {
            m =m *2;
            deep++;
        }
        bool first = true;
//      memset(rec,0,sizeof(rec));
//      memset(save,0,sizeof(save));
        flag = false;
//      rec[0] = 1;
//      rec[1] = 2;
//      rec[2] = 4;
//      fsize = 1000000;
//      dfs(4,3);   
        while(1) {
            dfs(0,deep);
            if(flag)
                break;
            deep++;
        }
        for(int i = 0; i <= deep ;i++) {
            if(first) {
                first = false;
                printf("%d",ans[i]);
            }
            else
                printf(" %d",ans[i]);
        }
        printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值