码迷,mamicode.com
首页 > 其他好文 > 详细

迭代加深搜索(IDDFS)

时间:2018-09-11 21:24:29      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:stream   code   namespace   int   math   ==   mes   lse   位置   

使用普通的DFS可能会让你把时间浪费在深度非常大而且答案不是最优的搜索过程上

些问题搜索时可能会存在搜索很深却得不到最优解的情况

那么我们就给搜索设置一个约束,当搜索深度达到约束值却还没找到可行解时结束搜索

如果我们在一个深度约束下没有搜索到答案,那么答案一定在更深的位置,那么就把约束深度调整到更深,然后再次搜索,直到搜索到答案为止

对当前的情况通过一个乐观估计函数进行预估,如果发现即使在最好的情况下搜索到当前的最深深度限制也没办法得到答案,那么就及时退出来实现剪枝

也就是传说中的IDA*

POJ3134

给定一个正整数n,求经过多少次乘法或除法运算可以从x得到xn,可以使用中间得到的结果

 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <string>
 6 #include <sstream>
 7 #include <algorithm>
 8 #include <cmath>
 9 #include <vector>
10 #include <stack>
11 #include <queue>
12 #include <list>
13 #define the_best_pony "Rainbow Dash"
14 
15 using namespace std;
16 
17 int n,maxh;
18 int a[1010];
19 
20 bool dfs(int x,int cur){
21     if(x<<(maxh-cur)<n) return false; //乐观估计剪枝,当前深度到限制深度指数最多增长2^(maxh-cur)倍 
22     if(cur>maxh) return false; //达到限制深度 
23     a[cur]=x;
24     if(x==n) return true;
25     for(int i=0;i<=cur;i++){
26         if(dfs(x+a[i],cur+1)) return true;
27         if(dfs(x>a[i]?x-a[i]:a[i]-x,cur+1)) return true;
28     }
29     return false;
30 }
31 
32 int main(){
33     while(scanf("%d",&n)&&n){
34         maxh=0;
35         memset(a,0,sizeof(a));
36         while(!dfs(1,0)){ //只要没找到答案就一直继续 
37             memset(a,0,sizeof(a)); 
38             maxh++; //增大深度限制 
39         }
40         printf("%d\n",maxh); //最大深度就是答案 
41     }
42     return 0;
43 }

 

迭代加深搜索(IDDFS)

标签:stream   code   namespace   int   math   ==   mes   lse   位置   

原文地址:https://www.cnblogs.com/aininot260/p/9629655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!