1 /****************************************************
2
3 Author : Coolxxx
4 Copyright 2017 by Coolxxx. All rights reserved.
5 BLOG : http://blog.csdn.net/u010568270
6
7 ****************************************************/
8 #include<bits/stdc++.h>
9 #pragma comment(linker,"/STACK:1024000000,1024000000")
10 #define abs(a) ((a)>0?(a):(-(a)))
11 #define lowbit(a) (a&(-a))
12 #define sqr(a) ((a)*(a))
13 #define mem(a,b) memset(a,b,sizeof(a))
14 const double EPS=1e-8;
15 const int J=10000;
16 const int MOD=100000007;
17 const int MAX=0x7f7f7f7f;
18 const double PI=3.14159265358979323;
19 const int N=304;
20 using namespace std;
21 typedef long long LL;
22 double anss;
23 LL aans;
24 int cas,cass;
25 int n,m,lll,ans;
26 int t[N][N],a[N][N],b[N][N],d[N][N],in[N][N];
27 int nex[N][N][2][2];
28 void tuopu()
29 {
30 int i,j,x,y,xx,yy;
31 mem(d,0);
32 queue<int>qx,qy;
33 for(i=1;i<=n;i++)
34 {
35 if(!in[i][a[i][1]])
36 {
37 d[i][a[i][1]]=t[i][a[i][1]];
38 qx.push(i);
39 qy.push(a[i][1]);
40 }
41 }
42 while(!qx.empty())
43 {
44 x=qx.front();qx.pop();
45 y=qy.front();qy.pop();
46 for(i=0;i<2;i++)
47 {
48 xx=nex[x][y][i][0];
49 yy=nex[x][y][i][1];
50 if(!x || !y)continue;
51 d[xx][yy]=max(d[xx][yy],d[x][y]+t[xx][yy]);
52 if(!--in[xx][yy])
53 {
54 qx.push(xx);
55 qy.push(yy);
56 }
57 }
58 ans=max(ans,d[x][y]);
59 }
60 }
61 int main()
62 {
63 #ifndef ONLINE_JUDGE
64 freopen("1.txt","r",stdin);
65 // freopen("2.txt","w",stdout);
66 #endif
67 int i,j,k,l;
68 int x,y,z;
69 // for(scanf("%d",&cass);cass;cass--)
70 // for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
71 // while(~scanf("%s",s))
72 while(~scanf("%d",&n))
73 {
74 ans=0;
75 mem(nex,0);mem(in,0);
76 scanf("%d",&m);
77 for(i=1;i<=n;i++)
78 for(j=1;j<=m;j++)
79 scanf("%d",&t[i][j]);
80 for(i=1;i<=n;i++)
81 for(j=1;j<=m;j++)
82 scanf("%d",&a[i][j]);
83 for(i=1;i<=m;i++)
84 for(j=1;j<=n;j++)
85 scanf("%d",&b[i][j]);
86 for(i=1;i<=n;i++)
87 {
88 for(j=1;j<m;j++)
89 {
90 nex[i][a[i][j]][0][0]=i,
91 nex[i][a[i][j]][0][1]=a[i][j+1];
92 in[i][a[i][j+1]]++;
93 }
94 }
95 for(i=1;i<=m;i++)
96 {
97 for(j=1;j<n;j++)
98 {
99 nex[b[i][j]][i][1][0]=b[i][j+1],
100 nex[b[i][j]][i][1][1]=i;
101 in[b[i][j+1]][i]++;
102 }
103 }
104 tuopu();
105 printf("%d\n",ans);
106 }
107 return 0;
108 }
109 /*
110 //
111
112 //
113 */