1. 程式人生 > >叠代加深搜索(IDDFS)

叠代加深搜索(IDDFS)

amp clas iostream 再次 tdi 問題搜索 情況下 一個 als

使用普通的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)