poj 2248 Addition Chains (迭代加深搜索)
2024-10-07 10:26:04
【题目描述】
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.
【题目链接】
【算法】
枚举构造答案,迭代加深搜索。
剪枝:
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;
}
最新文章
- 开源一个跨平台运行的服务插件 - TaskCore.MainForm
- thinkphp3.2.3之自动完成的实现
- 浏览器与web客户端的HTTP交互过程
- 如何更改tableView cell的accessoryView位置,如何让首尾的Separator不显示
- [问题2014S06] 解答
- Jquery easyui-combobox 的一个BUG
- Python关键字参数
- Python小例子
- JNI编程,C++调用Java
- UVa 10601 (Polya计数 等价类计数) Cubes
- 如何用 iptables 禁止某个ip?
- golang 阻塞的坑
- ZOJ 2972 Hurdles of 110m 【DP 背包】
- ORACLE查看和更改的最大连接数
- MurMurHash3
- scanf和gets的差别
- windows 10下通过python3.6成功搭建jupyter 服务器
- Python包中__init__.py作用
- bootstrap表格添加按钮、模态框实现
- Zabbix3.x 监控磁盘IO与自定义模板