博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
poj2248——Addition Chains(迭代加深搜索)
阅读量:4698 次
发布时间:2019-06-09

本文共 2005 字,大约阅读时间需要 6 分钟。

Description

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 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.

Input

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.

Output

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. 

Sample Input

571215770

Sample Output

1 2 4 51 2 4 6 71 2 4 8 121 2 4 5 10 151 2 4 8 9 17 34 68 77 迭代加深,注意剪枝(见代码中):

#include<iostream>

#include<cstdio>
#include<cstring>
using namespace std;
bool q=false;
int n,best,deep;
int v[105],ans[105];
void dfs(int x)
{
  if(q==false)//这里一定要判断,不然超时(读者自行思考)
  {
    if(v[x]==n)
    {
      best=x;
      for(int i=0;i<=x;i++)
      ans[i]=v[i];
      q=true;
      return ;
    }
    else if(x<deep)
    {
      for(int i=x;i>=0;i--)
      {
        if(v[i]*2>v[x])//剪枝1
        for(int j=x;j>=0;j--)
        if(v[i]+v[j]>=v[x]&&v[i]+v[j]<=n)//剪枝2
        {
          v[x+1]=v[i]+v[j];
          dfs(x+1);
        }
      }
    }
  }
  return ;
}
int main()
{
  while(~scanf("%d",&n)&&n>0)
  {
    memset(v,0,sizeof(v));
    memset(ans,0,sizeof(ans));
    q=false;
    deep=1;best=n;
    while(q==false)
    {
      v[0]=1;
      dfs(0);
      deep++;
    }
    for(int i=0;i<=best;i++)
    printf("%d ",ans[i]);
    printf("\n");
  }
  return 0;
}

 

转载于:https://www.cnblogs.com/937337156Zhang/p/5929675.html

你可能感兴趣的文章
[NYIST15]括号匹配(二)(区间dp)
查看>>
json_value.cpp : fatal error C1083: 无法打开编译器生成的文件:No such file or directory
查看>>
洛谷 P1101 单词方阵
查看>>
Swift DispatchQueue
查看>>
C#和JAVA 访问修饰符
查看>>
小甲鱼OD学习第1讲
查看>>
HDU-1085 Holding Bin-Laden Captive-母函数
查看>>
php提示undefined index的几种解决方法
查看>>
LRJ
查看>>
Struts2环境搭建
查看>>
Linux: Check version info
查看>>
stl学习之测试stlen,cout等的运行速度
查看>>
魔戒三曲,黑暗散去;人皇加冕,光明归来
查看>>
Error和Exception
查看>>
Python和Singleton (单件)模式[转载]
查看>>
httpclient设置proxy与proxyselector
查看>>
IT常用单词
查看>>
拓扑排序
查看>>
NYOJ--32--SEARCH--组合数
查看>>
JMS
查看>>