1310: Addition Chains

1310: Addition Chains


Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
3s 8192K 205 90 Standard

An addition chain for n is an integer sequence with the following four properties:

 

  • a0 = 1
  • am = n
  • a012<...m-1m
  • For each k ( ) there exist two (not neccessarily different) integers i and j ( ) with ak =ai +aj

You are given an integer n. Your job is to construct an addition chain for n with minimal length.

 

Input Specification

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

Output Specification

For each test case, print one line containing the minimal length.

 


Hint: The problem is a little time-critical, so use proper break conditions where necessary to reduce the search space.

Sample Input

5
7
12
15
77
0

Sample Output

4
5
5
6
9
#include
#include
using namespace std;
int a[1005],n,minlen;
void dfs(int step)
{
    if(step>minlen) return ;
    for(int i=step-1;i>=0;i--)
    {
        a[step]=a[step-1]+a[i];
        if(a[step]>n) continue;
        if(a[step]==n)
        {
            if(step+1            return ;
        }
        dfs(step+1);
    }
}                 
int main()
{
    while(cin>>n&&n)
    {
        if(n==1) {cout<<1<        a[0]=1;
        minlen=(1<<31)-1;
        dfs(1);
        cout<    }
    return 0;
}       
       
       

你可能感兴趣的:(joj,acm_dfs)