【题目描述】

	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.

【题目链接】

Addition Chains

【算法】

枚举构造答案,迭代加深搜索。
剪枝:
1、从大到小枚举i,j
2、排除冗余(判重)

【代码】

#include <stdio.h>
#include <cstring>
using namespace std;
int n,deep;
int ans[1000],v[1000];
bool dfs(int cur) {
if(cur>deep) {
if(ans[deep]==n) return 1;
return 0;
}
for(int i=cur-1;i>=0;i--) {
for(int j=i;j>=0;j--) {
if(ans[i]+ans[j]<=n&&!v[ans[i]+ans[j]]) {
ans[cur]=ans[i]+ans[j]; v[ans[i]+ans[j]]=1;
if(dfs(cur+1)) return 1;
v[ans[i]+ans[j]]=0;
}else if(ans[i]+ans[j]<=ans[cur-1]) break;
}
}
return 0;
}
int main() {
while(~scanf("%d",&n)&&n) {
printf("1"); ans[0]=1;
if(n==1) { puts(""); continue; }
for(deep=1;!dfs(1);deep++) memset(v,0,sizeof(v));
for(int i=1;i<=deep;i++) printf(" %d",ans[i]);
puts("");
}
return 0;
}

最新文章

  1. 开源一个跨平台运行的服务插件 - TaskCore.MainForm
  2. thinkphp3.2.3之自动完成的实现
  3. 浏览器与web客户端的HTTP交互过程
  4. 如何更改tableView cell的accessoryView位置,如何让首尾的Separator不显示
  5. [问题2014S06] 解答
  6. Jquery easyui-combobox 的一个BUG
  7. Python关键字参数
  8. Python小例子
  9. JNI编程,C++调用Java
  10. UVa 10601 (Polya计数 等价类计数) Cubes
  11. 如何用 iptables 禁止某个ip?
  12. golang 阻塞的坑
  13. ZOJ 2972 Hurdles of 110m 【DP 背包】
  14. ORACLE查看和更改的最大连接数
  15. MurMurHash3
  16. scanf和gets的差别
  17. windows 10下通过python3.6成功搭建jupyter 服务器
  18. Python包中__init__.py作用
  19. bootstrap表格添加按钮、模态框实现
  20. Zabbix3.x 监控磁盘IO与自定义模板

热门文章

  1. 3.docker镜像管理基础
  2. 047:创建和映射ORM模型
  3. JavaWeb DOM1
  4. js-点出弹框后(除了点击窗口上的叉子),点其他地方能够关闭窗口???
  5. java 8 接口默认方法
  6. express 和 pm2 建立博客
  7. AT2370 Piling Up
  8. SSM整合--------试题分析
  9. 我用HTML写简历
  10. RHEL6 kernel bug在hadoop上的测试