CLOCK - Chỉnh đồng hồ

Tác giả: flashmt

Ngôn ngữ: Pascal

const fi='';
      fo='';
      num:array[0..8] of longint=(4,3,4,3,5,3,4,3,4);
      max=262144;
var b:array[0..8,1..5] of longint;
    p,d,c,a:array[0..9] of longint;
    f:array[0..max,0..9] of longint;

procedure rf;
var i,j:longint; c:char;
begin
     assign(input,fi);
     reset(input);
     for i:=1 to 3 do
     begin
          for j:=1 to 3 do
          begin
               read(c);
               a[i*3+j-3]:=ord(c)-48;
          end;
          readln;
     end;
     close(input);
end;

procedure init;
var i:longint;
begin
     b[0,1]:=1; b[0,2]:=2; b[0,3]:=4; b[0,4]:=5;
     for i:=1 to 3 do b[1,i]:=i;
     b[2,1]:=2; b[2,2]:=3; b[2,3]:=5; b[2,4]:=6;
     for i:=1 to 3 do b[3,i]:=3*i-2;
     b[4,1]:=2; for i:=2 to 4 do b[4,i]:=i+2; b[4,5]:=8;
     for i:=1 to 3 do b[5,i]:=3*i;
     b[6,1]:=4; b[6,2]:=5; b[6,3]:=7; b[6,4]:=8;
     for i:=1 to 3 do b[7,i]:=6+i;
     b[8,1]:=5; b[8,2]:=6; b[8,3]:=8; b[8,4]:=9;
     p[0]:=1;
     for i:=1 to 9 do p[i]:=p[i-1] shl 2;
end;

procedure att(i:longint);
var j,s,k:longint;
begin
     for j:=0 to 3 do
     begin
          d[i]:=j;
          for k:=1 to num[i] do
              c[b[i,k]]:=(c[b[i,k]]+j) and 3;
          if i=8 then
          begin
               s:=0;
               for k:=0 to 8 do s:=s+d[k]*p[k];
               for k:=1 to 9 do f[s,k]:=c[k];
               f[s,0]:=0;
               for k:=0 to 8 do f[s,0]:=f[s,0]+d[k];
          end
          else att(i+1);
          for k:=1 to num[i] do
              c[b[i,k]]:=(c[b[i,k]]+4-j) and 3;
     end;
end;

procedure pr;
var i,j:longint;
begin
     init;
     att(0);
end;

procedure wf;
var re,i,j:longint; kt:boolean;
begin
     assign(output,fo);
     rewrite(output);
     re:=100;
     for i:=0 to max do
     begin
          kt:=true;
          for j:=1 to 9 do
              if (f[i,j]+a[j]) and 3<>0 then
              begin
                   kt:=false;
                   break;
              end;
          if kt and (f[i,0]<re) then re:=f[i,0];
     end;
     write(re);
     close(output);
end;

begin
     rf;
     pr;
     wf;
end.

Download