水dp,状态表示三个司机当前在哪所用最小耗油,因为有一个一定在当前点所以可以压掉一维
var f,w,d:array[..,..] of longint;
a:array[..] of longint;
x,y,i,j,k,n,ans:longint; function min(a,b:longint):longint;
begin
if a>b then exit(b) else exit(a);
end; procedure clear;
var i,j:longint;
begin
for i:= to n do
for j:=i to n do
f[i,j]:=;
end; procedure get(a,b:longint);
begin
if a>b then
begin
x:=b;
y:=a;
end
else begin
x:=a;
y:=b;
end;
end; begin
readln(n);
for i:= to n do
begin
for j:= to n do
begin
read(d[i,j]);
w[i,j]:=;
end;
readln;
end;
w[,]:=;
a[]:=;
i:=;
while not eoln do
begin
inc(i);
read(a[i]);
clear;
for j:= to n do
for k:=j to n do
begin
f[j,k]:=min(f[j,k],w[j,k]+d[a[i-],a[i]]);
get(a[i-],j);
f[x,y]:=min(f[x,y],w[j,k]+d[k,a[i]]);
get(a[i-],k);
f[x,y]:=min(f[x,y],w[j,k]+d[j,a[i]]);
end;
w:=f;
end;
ans:=;
for i:= to n do
begin
for j:=i to n do
ans:=min(ans,f[i,j]);
end;
writeln(ans);
end.