首页 > 专题系列 > Java解POJ > POJ 2248 Addition Chains [解题报告] Java
2013
11-11

POJ 2248 Addition Chains [解题报告] Java

Addition Chains

问题描述 :

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.

  2. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。