启发式迭代加深搜索(IDA*)学习笔记
首先认识一个东西:估价函数f(x) .
- 它表示在现有搜索状态下最少要走的步数(最幸运的情况,不一定取得到),其作用便是:若当前步数+
f(x)>maxdep 则退出。 - 估价函数
f(x) 的好坏,在很大程度上决定了IDA*算法的时间复杂度,如f(x)=0 即为爆搜。 - 来看一个例题:P2324 骑士精神
- 这题首先是要IDA*的,否则T飞。
- 那么,我们肯定是要让空格移动的,否则这么多马枚举一遍不就T飞了吗。
- 如何写估价函数?
- 最优情况就是空格每走一步都归位一个棋子,那么
f() 即为当前局面与目标局面不同棋子数量了。 -
### $code: #include <bits/stdc++.h> using namespace std; #define rx register const int maxn=10; const int dx[maxn]={0,1,1,-1,-1,2,2,-2,-2}; const int dy[maxn]={0,2,-2,2,-2,1,-1,1,-1};//步数 const int mason[maxn][maxn]={//2是空格,0白,1黑 {0,0,0,0,0,0}, {0,1,1,1,1,1}, {0,0,1,1,1,1}, {0,0,0,2,1,1}, {0,0,0,0,0,1}, {0,0,0,0,0,0} }; int n,m,t,now[maxn][maxn],sx,sy,flag;//flag是否成功 inline int f()//估价函数 { int tot=0; for(int i=1;i<=5;i++) { for(int j=1;j<=5;j++) { if(now[i][j]!=mason[i][j])tot++; } } return tot; } void IDA_star(int step,int x,int y,int mdep)//mdep最大深度 { if(step==mdep) { if(!f())flag=1;//全部归位 return; } for(int i=1;i<=8;i++) { int nx=x+dx[i],ny=y+dy[i]; if(nx<1 || nx>5 || ny<1 || ny>5)continue;//手欠打错了调了30minQwQ swap(now[x][y],now[nx][ny]); if(step+f()<=mdep) { IDA_star(step+1,nx,ny,mdep); } swap(now[x][y],now[nx][ny]);//回溯 } } char ch; signed main() { scanf("%d",&t); while(t--) { flag=0; for(rx int i=1;i<=5;i++) { for(rx int j=1;j<=5;j++) { cin>>ch; if(ch=='*') { sx=i,sy=j; now[i][j]=2; } else now[i][j]=ch-'0'; } } if(!f()) { printf("0\n"); continue; } for(rx int mdep=1;mdep<=15;mdep++) { IDA_star(0,sx,sy,mdep); if(flag) { printf("%d\n",mdep); break; } } if(!flag)printf("-1\n"); } return 0; }(未完待续)