您的位置:首页 > 其它

1054: [HAOI2008]移动玩具 - BZOJ

2014-04-08 20:20 260 查看
Description

在一个4*4的方框内摆放了若干个相同的玩具,某人想将这些玩具重新摆放成为他心中理想的状态,规定移动时只能将玩具向上下左右四个方向移动,并且移动的位置不能有玩具,请你用最少的移动次数将初始的玩具状态移动到某人心中的目标状态。
Input

前4行表示玩具的初始状态,每行4个数字1或0,1表示方格中放置了玩具,0表示没有放置玩具。接着是一个空行。接下来4行表示玩具的目标状态,每行4个数字1或0,意义同上。
Output

一个整数,所需要的最少移动次数。
Sample Input
1111
0000
1110
0010

1010
0101
1010
0101
Sample Output
4

直接搜就行了

囧,本来以为迭代深搜可以行的,但是悲剧的TLE了

好吧我还是写广搜吧

const
fx:array[1..4]of longint=(-4,4,1,-1);
var
f,q:array[0..1 shl 16]of longint;
start,goal,head,tail:longint;

procedure bfs;
var
i,j,s:longint;
begin
head:=1;
tail:=1;
q[1]:=start;
while f[goal]>1<<20 do
begin
for i:=1 to 16 do
for j:=1 to 4 do
if (i+fx[j]>0) and (i+fx[j]<17) and ((i and 3<>0) or (fx[j]<>1)) and ((i and 3<>1) or (fx[j]<>-1)) then
if (q[head] and (1<<(i-1))>0) and (q[head] and (1<<(i+fx[j]-1))=0) then
begin
s:=q[head]-(1<<(i-1))+(1<<(i+fx[j]-1));
if f[s]>1<<20 then
begin
f[s]:=f[q[head]]+1;
inc(tail);
q[tail]:=s;
end;
end;
inc(head);
end;
end;

procedure main;
var
i,j:longint;
s:char;
begin
for i:=1 to 4 do
for j:=1 to 4 do
begin
repeat
read(s);
until (s='1') or (s='0');
start:=(start<<1)+ord(s)-ord('0');
end;
for i:=1 to 4 do
for j:=1 to 4 do
begin
repeat
read(s);
until (s='1') or (s='0');
goal:=(goal<<1)+ord(s)-ord('0');
end;
fillchar(f,sizeof(f),1);
f[start]:=0;
bfs;
write(f[goal]);
end;

begin
main;
end.


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: