【宽搜】Vijos P1206 CoVH之再破难关

题目链接:

  https://vijos.org/p/1206

题目大意:

  给你开始和结束两张4x4的01图,每次操作只能够交换相邻的两个格子(有公共边),问最少的操作步数。

题目思路:

  【搜索】

  这题一看就是一道BFS(宽搜),判重的时候2进制压位就好,总共16位,最大不会超过216 -1(65535)。

 

  1 //
  2 //by coolxxx
  3 //
  4 #include<iostream>
  5 #include<algorithm>
  6 #include<string>
  7 #include<iomanip>
  8 #include<memory.h>
  9 #include<time.h>
 10 #include<stdio.h>
 11 #include<stdlib.h>
 12 #include<string.h>
 13 #include<stdbool.h>
 14 #include<math.h>
 15 #define min(a,b) ((a)<(b)?(a):(b))
 16 #define max(a,b) ((a)>(b)?(a):(b))
 17 #define abs(a) ((a)>0?(a):(-(a)))
 18 #define lowbit(a) (a&(-a))
 19 #define sqr(a) (a)*(a)
 20 #define swap(a,b) (a)^=(b),(b)^=(a),(a)^=(b)
 21 #define eps 1e-8
 22 #define S 10000
 23 #define MAX 0x7f7f7f7f
 24 #define PI 3.1415926535897
 25 #define N 24
 26 #define M 65544
 27 using namespace std;
 28 int n,m,cas,lll,ans;
 29 int r[N]={1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536};
 30 char s1[N];
 31 int map[4][4];
 32 int dx[4]={1,-1,0,0};
 33 int dy[4]={0,0,1,-1};
 34 int s,e;
 35 int q[M],v[M];
 36 bool u[M];
 37 int work()
 38 {
 39     int i,j,k,h,t,now,xx,yy,x;
 40     q[1]=e;h=0;t=1;
 41     while(h++<t)
 42     {
 43         now=q[h];
 44         if(now==s)return v[h];
 45         for(i=0;i<4;i++)
 46         {
 47             for(j=0;j<4;j++)
 48             {
 49                 for(k=0;k<4;k++)
 50                 {
 51                     xx=i+dx[k];
 52                     yy=j+dy[k];
 53                     if(0<=xx && xx<4 && 0<=yy && yy<4)
 54                     {
 55                         map[i][j]=(now&r[15-i*4-j])>0;map[xx][yy]=(now&r[15-4*xx-yy])>0;
 56                         x=now-map[i][j]*r[15-i*4-j]+map[i][j]*r[15-4*xx-yy]+map[xx][yy]*r[15-4*i-j]-map[xx][yy]*r[15-xx*4-yy];
 57                         if(!u[x])
 58                         {
 59                             u[x]=1;
 60                             q[++t]=x;
 61                             v[t]=v[h]+1;
 62                         }
 63                     }
 64                 }
 65             }
 66         }
 67     }
 68 }
 69 int main()
 70 {
 71     #ifndef ONLINE_JUDGE
 72     freopen("1.txt","r",stdin);
 73 //    freopen("2.txt","w",stdout);
 74     #endif
 75     int i,j,k;
 76 //    while(~scanf("%d",&n) && n)
 77 //    {
 78         for(i=0,j=15;i<4;i++)
 79         {
 80             scanf("%s",s1);
 81             for(k=0;k<4;k++,j--)
 82                 s+=(s1[k]-'0')*r[j];
 83         }
 84         for(i=0,j=15;i<4;i++)
 85         {
 86             scanf("%s",s1);
 87             for(k=0;k<4;k++,j--)
 88             {
 89                 e+=(s1[k]-'0')*r[j];
 90                 map[i][k]=s1[k]-'0';
 91             }
 92         }
 93         printf("%d\n",work());
 94 //    }
 95     return 0;
 96 }
 97 
 98 
 99 /*
100 //
101 
102 //
103 */
View Code

 

posted @ 2016-03-22 20:00  Cool639zhu  阅读(346)  评论(0编辑  收藏  举报