2013
11-11

# POJ 2248 Addition Chains [解题报告] Java

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 (1<=k<=m) there exist two (not necessarily 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.

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

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

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

5
7
12
15
77
0


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


/* @author: */
import java.util.Scanner;
public class Main{
static int arr[]=new int[20];
static int n,minn;
static int save[]=new int[20];

static void bfs(int a)
{
int i,j;
if(a>=minn)return;
if(arr[a-1]==n)
{
if(a< minn){
minn=a;
for(i=0;i< a;i++)
save[i]=arr[i];
}
return;
}
for(i=a-1;i>=0;i--)
{
for(j=i;j>=0;j--)
{
if(arr[i]+arr[j]>n)continue;
if(arr[i]+arr[j]<=arr[a-1])continue;
arr[a]=arr[i]+arr[j];
if(a==minn-2&&arr[a]< n)break;
bfs(a+1);
}
if(j!=0)break;
}
}

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
while(sc.hasNext())
{
n=sc.nextInt();
if(n==0) break;
minn=11;
arr[0]=1;
bfs(1);
for(int k=0;k< minn-1;k++)
System.out.printf("%d ",save[k]);
System.out.printf("%d\n",save[minn-1]);
}
}
}

1. Good task for the group. Hold it up for every yeara??s winner. This is a excellent oppotunity for a lot more enhancement. Indeed, obtaining far better and much better is constantly the crucial. Just like my pal suggests on the truth about ab muscles, he just keeps obtaining much better.