Addition Chains

前言

最讨厌英文题了(因为读不懂

题目描述

An addition chain for n is an integer sequence < a0, a1, a2, … , am > with the following four properties:
• a0 = 1
• am = n
• a0 < a1 < a2 < · · · < am−1 < am
• For each k (1 ≤ k ≤ m) there exist two (not neccessarily different) integers i and j (0 ≤ i, j ≤ k−1)
with ak = ai + aj
You are given an integer n. Your job is to construct an addition chain for n with minimal length.
If there is more than one such sequence, any one is acceptable.
For example, < 1, 2, 3, 5 > and < 1, 2, 4, 5 > are both valid solutions when you are asked for an
addition chain for 5.

Input

The input file will contain one or more test cases. Each test case consists of one line containing one
integer n (1 ≤ n ≤ 10000). Input is terminated by a value of zero (0) for n.

Output

For each test case, print one line containing the required integer sequence. Separate the numbers by
one blank.

Sample Input

5
7
12
15
77
0

Sample Output

1 2 4 5
1 2 4 6 7
1 2 4 8 12
1 2 4 5 10 15
1 2 4 8 9 17 34 68 77

题意

给你一个n,要求一个<1……n>的序列,每一个数必须比前面的书都大,并且是前面任意两数的和(这两个数可以相等)

分析

没有给出长度,那还怎么去搜索啊!
没关系,有一种奇葩的搜索叫“迭代加深搜索”
每一次搜索的时候,我们都枚举序列的长度就行了
然后去找在这层的正确解

对这道题,有一个小小的优化
大意就是说,就算每次都取最大值,如果到了最后还是小于n的话,那这个分支一定是无解的


下为核心搜索部分

bool dfs(int x){
    if(x==depth){
        if(vec[x-1]==n) return true;
        return false;   
    }
    int i=x-1;
    for(int j=i;j>=0;j--)
        if(vec[i]+vec[j]>vec[x-1]){//这是个优化,默认有一个加数为vec[i-1],也就是目前最大的数
            if(vec[i]+vec[j]>n) continue;//每个数都必须<=n
            vec[x]=vec[i]+vec[j];
            int sum=vec[x];
            sum*=p[depth-x];
            if(sum<n) return false;
            if(dfs(x+1)) return true;
        } else break;
    return false;
}

代码

#include<cmath>
#include<cstdio>
#include<vector>
using namespace std;
#define MAXN 10000
int vec[MAXN+5]={1},depth,n,p[MAXN+5]={0,1};
bool dfs(int x){
    if(x==depth){
        if(vec[x-1]==n) return true;
        return false;   
    }
    int i=x-1;
    for(int j=i;j>=0;j--)
        if(vec[i]+vec[j]>vec[x-1]){
            if(vec[i]+vec[j]>n) continue;
            vec[x]=vec[i]+vec[j];
            int sum=vec[x];
            sum*=p[depth-x];
            if(sum<n) return false;
            if(dfs(x+1)) return true;
        } else break;
    return false;
}
int main(){
    for(int i=2;i<=MAXN;i++)
        p[i]=1<<(i-1);
    while(scanf("%d",&n)&&n!=0){
        if(n==2){
            printf("1 2\n");    
            continue;
        }
        depth=(int)log2(n);
        while(1){
            if(dfs(1)){
                printf("1");
                for(int i=1;i<depth;i++)
                    printf(" %d",vec[i]);
                printf("\n");
                break;
            }
            depth++;
        }
    }
    return 0;
}

感想

怎么每次做迭代加深搜索都感觉是在写暴力+一堆乱七八糟的优化

posted @ 2018-04-08 14:00  SteinGate  阅读(99)  评论(0编辑  收藏  举报