算法:搜索
灰常经典的问题啊,话说开始的时候就会写个裸的BFS,这次写加了个HASH,竟然过了。
灰常经典的问题啊,话说开始的时候就会写个裸的BFS,这次写加了个HASH,竟然过了。
总之就是移动0,然后四个方向随便乱搞就AC了~
注意要限制一下字符串的长度,否则会MLE的~
program vijos1360;
const
maxh=3000011;
var
hashh,dep:array [0..maxh] of longint;
b:array [0..maxh] of boolean;
que:array [0..maxh] of string[9];
head,tail:longint;
function hash(x:string):longint;
var
i,xx:longint;
begin
val(x,xx);
i:=xx mod maxh;
while (hashh[i]<>0) and (hashh[i]<>xx) do
begin
inc(i);
if i>maxh then i:=i mod maxh;
end;
if hashh[i]=0 then hashh[i]:=xx;
exit(i);
end;
procedure init;
begin
head:=0;
tail:=1;
readln(que[1]);
dep[hash(que[1])]:=0;
b[hash(que[1])]:=true;
end;
procedure BFS;
var
x,tx:string;
ch:char;
t:longint;
begin
while head<tail do
begin
inc(head);
x:=que[head];
t:=pos('0',x);
if t-3>0 then
begin
tx:=x;
ch:=tx[t];
tx[t]:=tx[t-3];
tx[t-3]:=ch;
if not b[hash(tx)] then
begin
if tx='123804765' then
begin
writeln(dep[hash(x)]+1);
close(input);
close(output);
halt;
end;
b[hash(tx)]:=true;
dep[hash(tx)]:=dep[hash(x)]+1;
inc(tail);
que[tail]:=tx;
end;
end;
if t mod 3<>1 then
begin
tx:=x;
ch:=tx[t];
tx[t]:=tx[t-1];
tx[t-1]:=ch;
if not b[hash(tx)] then
begin
if tx='123804765' then
begin
writeln(dep[hash(x)]+1);
close(input);
close(output);
halt;
end;
b[hash(tx)]:=true;
dep[hash(tx)]:=dep[hash(x)]+1;
inc(tail);
que[tail]:=tx;
end;
end;
if t mod 3<>0 then
begin
tx:=x;
ch:=tx[t];
tx[t]:=tx[t+1];
tx[t+1]:=ch;
if not b[hash(tx)] then
begin
if tx='123804765' then
begin
writeln(dep[hash(x)]+1);
close(input);
close(output);
halt;
end;
b[hash(tx)]:=true;
dep[hash(tx)]:=dep[hash(x)]+1;
inc(tail);
que[tail]:=tx;
end;
end;
if t+3<10 then
begin
tx:=x;
ch:=tx[t];
tx[t]:=tx[t+3];
tx[t+3]:=ch;
if not b[hash(tx)] then
begin
if tx='123804765' then
begin
writeln(dep[hash(x)]+1);
close(input);
close(output);
halt;
end;
b[hash(tx)]:=true;
dep[hash(tx)]:=dep[hash(x)]+1;
inc(tail);
que[tail]:=tx;
end;
end;
end;
end;
begin
assign(input,'VJ1360.in'); reset(input);
assign(output,'VJ1360.out'); rewrite(output);
init;
BFS;
close(input); close(output);
end.