zoukankan      html  css  js  c++  java
  • 搜索:迭代加深搜索

    使用普通的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
    ",maxh); //最大深度就是答案 
    41     }
    42     return 0;
    43 }
  • 相关阅读:
    linux下tomcat启动正常,但是外部浏览器无法访问
    mybatis中映射文件和实体类的关联性
    判断用户请求时使用的浏览器类型
    HTML地理位置定位
    使用jQuery的toggle()方法对HTML标签进行显示、隐藏操作
    jQuery怎么去掉标签的hover效果
    java与javascript
    sendRedirect 与forward的区别
    windows--添加程序到右键菜单中
    收集:word xml格式
  • 原文地址:https://www.cnblogs.com/aininot260/p/9629655.html
Copyright © 2011-2022 走看看