概述
题目连接:http://poj.org/problem?id=2248
题目大意:现在有一个数组其中a[1] = 1,a[m] = n,并且a[1] < a[2] < ........< a[m],现在给你一个数n问,满足条件的m的最小值为多少。其中1 <= n <= 9
大致思路:如果我们按照DFS直接搜索的话,一共有n!个节点十分耗时,这个时候我们可以采用迭代加深搜索,每一次搜索限定好搜索深度,并逐层增加搜索深度,知道找到答案为止。
代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 110;
bool vis[MAXN];
int ans[MAXN];
int maxd,n;
bool DFS(int d){
if(d > maxd){
if(ans[maxd] == n) return true;
else return false;
}
memset(vis,0,sizeof(vis));
for(int i = d - 1; i >= 1; i--){
for(int j = d - 1; j >= 1; j--){
if(ans[i] + ans[j] <= ans[d - 1]) break;
if(!vis[ans[i] + ans[j]] && ans[i] + ans[j] <= n){
ans[d] = ans[i] + ans[j];
vis[ans[d]] = 1;
if(DFS(d + 1)) return true;
}
}
}
return false;
}
int main(int argc, char const *argv[])
{
while(~scanf("%d",&n) && n){
bool ok = false;
ans[1] = 1;
//ans[0] = 0;
if(n == 1) { cout << "1" << endl; continue; }
for(maxd = 2; ; maxd++){
memset(vis,0,sizeof(vis));
if(DFS(2)) { ok = true; break; }
}
//cout << maxd << endl;
if(ok){
for(int i = 1; i < maxd; i++) cout << ans[i] << " ";
cout << ans[maxd] << endl;
}
}
return 0;
}
最后
以上就是阔达咖啡为你收集整理的POJ2248——Addition Chains【DFS,迭代加深搜索】的全部内容,希望文章能够帮你解决POJ2248——Addition Chains【DFS,迭代加深搜索】所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复