uva529

题目:
An addition chain for n is an integer sequence <a0,a1,a2,,am> 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;
}

你可能感兴趣的:(uva529)