【BZOJ】【1085】【SCOI2005】骑士精神

IDA*算法

  Orz HZWER

  A*+迭代加深搜索=IDA*

  这题的估价相当于一个可行性剪枝,即如果当前走的步数s+未归位的点数>搜索深度k,则剪枝

  

 1 /**************************************************************
 2     Problem: 1085
 3     User: Tunix
 4     Language: C++
 5     Result: Accepted
 6     Time:1388 ms
 7     Memory:1272 kb
 8 ****************************************************************/
 9  
10 //BZOJ 1085
11 #include<cstdio>
12 #include<cstdlib>
13 #include<cstring>
14 #include<iostream>
15 #include<algorithm>
16 #define rep(i,n) for(int i=0;i<n;++i)
17 #define F(i,j,n) for(int i=j;i<=n;++i)
18 #define D(i,j,n) for(int i=j;i>=n;--i)
19 using namespace std;
20  
21 int getint(){
22     int v=0,sign=1; char ch=getchar();
23     while(ch<'0'||ch>'9') {if (ch=='-') sign=-1; ch=getchar();}
24     while(ch>='0'&&ch<='9') {v=v*10+ch-'0'; ch=getchar();}
25     return v*=sign;
26 }
27 /*******************tamplate********************/
28 int k;
29 const int ans[5][5]={{1,1,1,1,1},
30                      {0,1,1,1,1},
31                      {0,0,2,1,1},
32                      {0,0,0,0,1},
33                      {0,0,0,0,0}};
34 const int fx[8]={1,1,-1,-1,2,2,-2,-2},
35           fy[8]={2,-2,2,-2,1,-1,1,-1};
36  
37 bool flag=0;
38 bool judge(int a[5][5]){
39     rep(i,5)
40         rep(j,5)
41             if (ans[i][j]!=a[i][j]) return 0;
42     return 1;
43 }
44 bool eva(int a[5][5],int s){
45     int v=0;
46     rep(i,5)
47         rep(j,5)
48             if (a[i][j]!=ans[i][j]){
49                 v++;
50                 if(v+s>k) return 0;
51             }
52     return 1;
53 }
54 //v¼´Îª¹À¼Ûº¯Êý£¨Èç¹û¸úans²î¾àÌ«´ó£¬²»¿ÉÄÜÔÚk²½Ö®ÄÚ³ö½â£¬ÔòÉáÆú
55 void search(int s,int a[5][5],int x,int y){
56     if (s==k) {if (judge(a)) flag=1; return;}
57     if (flag==1) return;
58     rep(i,8){
59         int tx=x+fx[i],ty=y+fy[i];
60         if (tx<0||tx>4||ty<0||ty>4) continue;
61         swap(a[x][y],a[tx][ty]);
62         if (eva(a,s)) search(s+1,a,tx,ty);
63         swap(a[x][y],a[tx][ty]);
64     }
65 }
66 int main(){
67     int T=getint();
68     char ch[10];
69     while(T--){
70         int a[5][5],x,y;
71         memset(a,0,sizeof a);
72         rep(i,5){
73             scanf("%s",ch);
74             rep(j,5)
75                 if (ch[j]=='*'){ a[i][j]=2;x=i;y=j; }
76                 else a[i][j]=ch[j]-'0';
77         }
78         flag=0;
79         for(k=1;k<=15;++k){
80             search(0,a,x,y); if (flag){ printf("%d\n",k);break;}
81         }
82         if (!flag) printf("-1\n");
83     }
84     return 0;
85 }
View Code

 

posted @ 2015-02-17 11:24  Tunix  阅读(135)  评论(0编辑  收藏