CLOCK - Chỉnh đồng hồ

Tác giả: ladpro98

Ngôn ngữ: Pascal

program CLOCK;
uses    math;
const   move:array[1..9,0..5] of longint = (
        (4,1,2,4,5,0),(3,1,2,3,0,0),(4,2,3,5,6,0),(3,1,4,7,0,0),
        (5,2,4,5,6,8),(3,3,6,9,0,0),(4,4,5,7,8,0),(3,7,8,9,0,0),(4,5,6,8,9,0));
        fi='';
var     q,d:array[0..1 shl 19] of longint;
        chk:array[0..1 shl 19] of boolean;
        c:char;st:string;
        l,r,u,v,i,s:longint;
        inp:text;

function get(x,m:longint):longint;
var     i,b:longint;
begin
        for i:=1 to move[m,0] do begin
                b:=x shr (2*move[m,i]-2) and 3;
                x:=x-b*(1 shl (2*move[m,i]-2));
                x:=x+((b+1) mod 4)*(1 shl (2*move[m,i]-2));
        end;
        exit(x);
end;

begin
        assign(inp,fi);reset(inp);
        while not eof(inp) do begin
                read(inp,c);
                if c in ['0'..'3'] then st:=c+st;
        end;
        for i:=1 to 9 do s:=s*4+ord(st[i])-48;
        l:=1;r:=1;
        q[1]:=s;d[s]:=0;chk[s]:=true;
        while l<=r do begin
                u:=q[l];inc(l);
                for i:=1 to 9 do begin
                        v:=get(u,i);
                        if not chk[v] then begin
                                inc(r);
                                q[r]:=v;
                                d[v]:=d[u]+1;
                                if v=0 then begin
                                        write(d[v]);halt;
                                end;
                                chk[v]:=true;
                        end;
                end;
        end;
        write(d[0]);
end.

Download