http://www.lydsy.com/JudgeOnline/problem.php?id=1054
無聊時想練一下構圖又懶得打廣搜……
發現狀態只有2^16種
於是根據相鄰狀態連邊
(最多隻有2^22條邊(極有可能不到))
然後直接跑最短路即可
代碼如下
#include <bits/stdc++.h>
using namespace std;
#define N 100005
#define M 4200000
#define inf 1000000000
char s[10];
int num,to[M],head[N],Next[M];
int dis[N],flag[N],a[4][4],b[4][4];
int n;
struct node
{
int x,y;
};
bool operator > (node x,node y)
{
return x.y<y.y;
}
bool operator < (node x,node y)
{
return x.y>y.y;
}
priority_queue <node> heap;
inline bool check1(int x,int y)
{
if (x>2)
if (a[x-2][y]^a[x-1][y]) return 0;
if (y)
if (a[x-1][y-1]^a[x-1][y]) return 0;
if (y<3)
if (a[x-1][y+1]^a[x-1][y]) return 0;
return 1;
}
inline bool check2(int x,int y)
{
if (x>2)
if (a[x-2][y]^a[x-1][y]) return 0;
if (y)
if (a[x-1][y-1]^a[x-1][y]) return 0;
return 1;
}
inline void add(int st,int x,int y,int xx,int yy)
{
swap(b[x][y],b[xx][yy]);
int t=0;
for (int i=3;i>=0;--i)
for (int j=3;j>=0;--j)
t=(t<<1)+(b[i][j]&1);
++num;
to[num]=t;
Next[num]=head[st];
head[st]=num;
swap(b[x][y],b[xx][yy]);
}
int main()
{
n=1<<16;
for (int i=0;i<(1<<16);++i)
{
int t=i;
for (int i1=0;i1<4;++i1)
for (int j1=0;j1<4;++j1)
a[i1][j1]=b[i1][j1]=t&1,t>>=1;
for (int i1=0;i1<4;++i1)
for (int j1=0;j1<4;++j1)
{
if (i1) if (a[i1][j1]^a[i1-1][j1]) if (check1(i1,j1)) add(i,i1,j1,i1-1,j1);
if (j1) if (a[i1][j1]^a[i1][j1-1]) if (check2(i1,j1)) add(i,i1,j1,i1,j1-1);
if (i1<3) if (a[i1][j1]^a[i1+1][j1]) add(i,i1,j1,i1+1,j1);
if (j1<3) if (a[i1][j1]^a[i1][j1+1]) add(i,i1,j1,i1,j1+1);
}
}
int st=0,ed=0;
for (int i=0;i<4;++i)
{
scanf("%s",s);
for (int j=0;j<4;++j) a[i][j]=s[j]-'0';
}
for (int i=3;i>=0;--i)
for (int j=3;j>=0;--j)
st=(st<<1)+(a[i][j]&1);
for (int i=0;i<4;++i)
{
scanf("%s",s);
for (int j=0;j<4;++j) a[i][j]=s[j]-'0';
}
for (int i=3;i>=0;--i)
for (int j=3;j>=0;--j)
ed=(ed<<1)+(a[i][j]&1);
//cout<<"st="<<st<<endl;cout<<"ed="<<ed<<endl;
for (int i=0;i<n;++i) dis[i]=inf,flag[i]=1;
dis[st]=0;
heap.push({st,0});
while (!heap.empty())
{
int t;
do
{
t=heap.top().x;
heap.pop();
}while (!flag[t]);
flag[t]=0;
for (int j=head[t];j;j=Next[j])
if (flag[to[j]] && dis[to[j]]>dis[t]+1)
{
dis[to[j]]=dis[t]+1;
heap.push({to[j],dis[to[j]]});
}
}
cout<<dis[ed]<<endl;
}