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
- a0<a1<a2<...<am-1<am
- 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 (
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<iostream>
#include<cstring>
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<minlen) minlen=step+1;
return ;
}
dfs(step+1);
}
}
int main()
{
while(cin>>n&&n)
{
if(n==1) {cout<<1<<endl;continue;}
a[0]=1;
minlen=(1<<31)-1;
dfs(1);
cout<<minlen<<endl;
}
return 0;
}