bzoj 1054
一看就想到BFS。
由于状态只有2^16个,所以直接状压。
建议用宏定义优化代码。
#include<cstdio> #include<cctype> #include<algorithm> #define t1 fr-(1<<i)+(1<<i+1) #define t2 fr-(1<<i)+(1<<i-1) #define t3 fr-(1<<i)+(1<<i+4) #define t4 fr-(1<<i)+(1<<i-4) using namespace std; const int maxs=65536; int read(){ char c; while(!isdigit(c=getchar())); return c-'0'; } int q[maxs],dis[maxs]; int main(){ int s=0,t=0; for(int i=0;i<16;i+=1) s|=read()<<i; for(int i=0;i<16;i+=1) t|=read()<<i; int l=0,w=0; q[w++]=s; dis[s]=1; while(l<w && !dis[t]){ int fr=q[l++]; for(int i=0;i<16;i+=1) if(fr&(1<<i)){ if(i%4!=3 && !(fr&(1<<i+1)) && !dis[t1]) dis[t1]=dis[fr]+1,q[w++]=t1; if(i%4 && !(fr&(1<<i-1)) && !dis[t2]) dis[t2]=dis[fr]+1,q[w++]=t2; if(i<=11 && !(fr&(1<<i+4)) && !dis[t3]) dis[t3]=dis[fr]+1,q[w++]=t3; if(i>=4 && !(fr&(1<<i-4)) && !dis[t4]) dis[t4]=dis[fr]+1,q[w++]=t4; } } printf("%d",dis[t]-1); return 0; }