VMKEY - Thế giới năm 1000003
Tác giả: ladpro98
Ngôn ngữ: Pascal
program vmkey;
uses math;
const fi='';
lim=10;
var s:ansistring;
a,px,py:array[0..10] of longint;
check:array[0..10] of boolean;
//row[0..9,0..9,0..9] of boolean;
f:array[0..10,0..10] of longint;
res:longint;
procedure input;
var inp:text;
i:longint;
begin
assign(inp,fi);
reset(inp);
readln(inp,s);
close(inp);
res:=high(longint);
for i:=2 to length(s) do
inc(f[min(ord(s[i]),ord(s[i-1]))-48,max(ord(s[i]),ord(s[i-1]))-48]);
end;
procedure update;
var i,j,m,t:longint;
begin
m:=1;
//row[a[1],a[2],a[3]]:=true;
for i:=1 to 3 do
for j:=1 to 3 do
begin
px[a[m]]:=i;
py[a[m]]:=j;
inc(m);
end;
px[a[m]]:=4;py[a[m]]:=1;
t:=0;
for i:=0 to 8 do
for j:=i+1 to 9 do
begin
inc(t,f[i,j]*(abs(px[i]-px[j])+abs(py[i]-py[j])));
if t>=res then exit;
end;
res:=min(res,t);
end;
procedure back(i:longint);
var j:longint;
begin
if i>lim then
begin
update;
exit;
end;
for j:=0 to 9 do
if not check[j] then
begin
check[j]:=true;
a[i]:=j;
back(i+1);
check[j]:=false;
end;
end;
begin
input;
back(1);
write(res);
end.