解题:SCOI 2005 骑士精神

题面

我把这个当做IDA*的模板题的说,说说我个人对IDA*的理解

IDA*是一个DFS,和A*一样,它也有一个乐观的估价函数。这里这个估价函数是用来限制状态的扩展的,如果当前代价加上乐观的估计都无法在规定层数内出解,我们就不向更深搜索了。这里取位置有差异的骑士个数作为估价函数即可,注意是骑士个数,因为在最后一步的时候我们有两个差异位置,然而实际上我们只要让一个骑士跳一步就可以完成了。这里我偷懒直接在差异位置上减掉了$1$......

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int goal[6][6]=
 6 {
 7     {0,0,0,0,0,0},
 8     {0,1,1,1,1,1},
 9     {0,0,1,1,1,1},
10     {0,0,0,2,1,1},
11     {0,0,0,0,0,1},
12     {0,0,0,0,0,0}
13 };
14 const int mov[8][2]=
15 {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};
16 int mapp[6][6]; char rd[6];
17 int T,sx,sy,lim,able;
18 int dif()
19 {
20     int ret=0;
21     for(int i=1;i<=5;i++)
22         for(int j=1;j<=5;j++)
23             ret+=(mapp[i][j]!=goal[i][j]);
24     return ret;
25 }
26 void IDAstar(int x,int y,int stp)
27 {
28     if(stp>lim) 
29     {
30         if(!dif()) able=true;
31         return ;
32     }
33     for(int i=0;i<8&&!able;i++)
34     {
35         int tx=x+mov[i][0],ty=y+mov[i][1];
36         if(tx>=1&&tx<=5&&ty>=1&&ty<=5) 
37         {
38             swap(mapp[x][y],mapp[tx][ty]);
39             if(dif()+stp-1<=lim) IDAstar(tx,ty,stp+1);
40             swap(mapp[x][y],mapp[tx][ty]);
41         }
42     }
43 }
44 int main ()
45 {
46     scanf("%d",&T);
47     while(T--)
48     {
49         for(int i=1;i<=5;i++)
50         {
51             scanf("%s",rd+1);
52             for(int j=1;j<=5;j++)
53                 if(rd[j]=='*') mapp[i][j]=2,sx=i,sy=j;
54                 else mapp[i][j]=(rd[j]-'0');
55         }
56         bool found=false;
57         if(!dif()) {puts("0"); continue;}
58         for(int i=1;i<=15;i++)
59         {
60             lim=i,able=false,IDAstar(sx,sy,1);
61             if(able) {printf("%d\n",i); found=true; break;}
62         }
63         if(!found) printf("-1\n");
64     }
65     return 0;
66 }
View Code

 

转载于:https://www.cnblogs.com/ydnhaha/p/9779579.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值