1 const maxn=2000000;
2 type node=record
3 from,go,next,w:longint;
4 end;
5 var i,j,n,cnt,tot,t,x,s,l,r,y:longint;
6 head,d,a,p:array[0..maxn] of longint;
7 v:array[0..maxn] of boolean;
8 e:array[0..maxn] of node;
9 num:array[0..600,0..600] of longint;
10 procedure insert(x,y,z:longint);
11 begin
12 inc(tot);
13 e[tot].from:=x;e[tot].go:=y;e[tot].w:=z;e[tot].next:=head[x];head[x]:=tot;
14 end;
15 procedure up(i:longint);
16 var t:longint;
17 begin
18 while (i>1) and (d[a[i]]<d[a[i>>1]]) do
19 begin
20 t:=a[i];a[i]:=a[i>>1];a[i>>1]:=t;
21 p[a[i]]:=i;p[a[i>>1]]:=i>>1;
22 i:=i>>1;
23 end;
24 end;
25 procedure down(i:longint);
26 var t,j:longint;
27 begin
28 j:=i<<1;
29 if (j<cnt) and (d[a[j+1]]<d[a[j]]) then inc(j);
30 while (j<=cnt) and (d[a[j]]<d[a[i]]) do
31 begin
32 t:=a[i];a[i]:=a[j];a[j]:=t;
33 p[a[i]]:=i;p[a[j]]:=j;
34 i:=j;j:=j<<1;
35 if (j<cnt) and (d[a[j+1]]<d[a[j]]) then inc(j);
36 end;
37 end;
38 procedure dijkstra;
39 begin
40 fillchar(d,sizeof(d),60);
41 fillchar(v,sizeof(v),false);
42 d[s]:=0;cnt:=0;
43 for i:=0 to n*n+1 do begin inc(cnt);a[cnt]:=i;p[i]:=cnt;up(cnt);end;
44 for j:=1 to n*n+1 do
45 begin
46 x:=a[1];a[1]:=a[cnt];dec(cnt);down(1);
47 v[x]:=true;
48 i:=head[x];
49 while i<>0 do
50 begin
51 y:=e[i].go;
52 if not(v[y]) and (d[x]+e[i].w<d[y]) then
53 begin
54 d[y]:=d[x]+e[i].w;
55 up(p[y]);
56 end;
57 i:=e[i].next;
58 end;
59 end;
60 end;
61
62 procedure init;
63 begin
64 readln(n);s:=0;t:=n*n+1;
65 for i:=1 to n do for j:=1 to n do num[i,j]:=(i-1)*n+j;
66 for i:=1 to n+1 do
67 for j:=1 to n do
68 begin
69 readln(x);
70 if i=1 then insert(num[i,j],t,x)
71 else if i=n+1 then insert(s,num[i-1,j],x)
72 else insert(num[i,j],num[i-1,j],x);
73 end;
74 for i:=1 to n do
75 for j:=1 to n+1 do
76 begin
77 readln(x);
78 if j=1 then insert(s,num[i,j],x)
79 else if j=n+1 then insert(num[i,j-1],t,x)
80 else insert(num[i,j-1],num[i,j],x);
81 end;
82 for i:=1 to n+1 do
83 for j:=1 to n do
84 begin
85 readln(x);
86 if i=1 then insert(t,num[i,j],x)
87 else if i=n+1 then insert(num[i-1,j],s,x)
88 else insert(num[i-1,j],num[i,j],x);
89 end;
90 for i:=1 to n do
91 for j:=1 to n+1 do
92 begin
93 readln(x);
94 if j=1 then insert(num[i,j],s,x)
95 else if j=n+1 then insert(t,num[i,j-1],x)
96 else insert(num[i,j],num[i,j-1],x);
97 end;
98 end;
99 procedure main;
100 begin
101 dijkstra;
102 writeln(d[t]);
103 end;
104 begin
105 assign(input,‘input.txt‘);assign(output,‘output.txt‘);
106 reset(input);rewrite(output);
107 init;
108 main;
109 close(input);close(output);
110 end.