Luogu P2324 [SCOI2005]骑士精神 搜索

刚开始写了个没迭代的。。。结果过了$qwq$

然后迭个代。。更快了。。

#include<cstdio>
#include<iostream>
#define R register int
using namespace std;
inline int g() {
    R ret=0,fix=1; register char ch; while(!isdigit(ch=getchar())) fix=ch=='-'?-1:fix;
    do ret=ret*10+(ch^48); while(isdigit(ch=getchar())); return ret*fix;
}
const int D[5][5]=
{{1,1,1,1,1},
 {0,1,1,1,1},
 {0,0,-6,1,1},
 {0,0,0,0,1,},
 {0,0,0,0,0}
};
const int dx[]={1,2,2,1,-1,-2,-2,-1},dy[]={2,1,-1,-2,-2,-1,1,2};
int T,a[5][5],ans,xx,yy,mxd;
inline int calc() { R ret=0;
    for(R i=0;i<=4;++i) for(R j=0;j<=4;++j) ret+=(a[i][j]!=D[i][j]); return ret;
}
inline bool ck(int x,int y) {return x<0||x>4||y<0||y>4;}
inline void dfs(int stp,int x,int y,int pre) { R tmp=calc();
    if(stp+tmp>mxd) return ;
    if(tmp==0) {ans=min(ans,stp-1); return ;}
    for(R i=0;i<=7;++i) { 
        if(pre!=-1&&(pre+4)%8==i) continue;
        R X=x+dx[i],Y=y+dy[i];
        if(ck(X,Y)) continue;
        swap(a[x][y],a[X][Y]); dfs(stp+1,X,Y,i);
        swap(a[x][y],a[X][Y]);
    }
}
signed main() { 
    T=g(); for(R i=1;i<=T;++i) { ans=0x3f3f3f3f;
        for(R i=0;i<=4;++i) for(R j=0;j<=4;++j) {
            register char ch; while(ch=getchar(),ch!='0'&&ch!='1'&&ch!='*'); 
            a[i][j]=ch-48; if(ch=='*') xx=i,yy=j;
        } for(mxd=1;mxd<=17&&ans==0x3f3f3f3f;++mxd) dfs(1,xx,yy,-1);  if(ans!=0x3f3f3f3f) printf("%d\n",ans); else printf("-1\n");
    }
} 

2019.07.03

 

posted @ 2019-07-03 20:00  LuitaryiJack  阅读(203)  评论(0编辑  收藏  举报