1 #include <iostream>
2 #include <cstdio>
3 #include <algorithm>
4 #include <cstring>
5 #include <queue>
6 #define rep(i,l,r) for(int i=l; i<=r; i++)
7 #define clr(x,y) memset(x,y,sizeof(x))
8 #define travel(x) for(Edge *p=last[x]; p; p=p->pre)
9 using namespace std;
10 const int INF = 0x3f3f3f3f;
11 const int maxn = 2000010;
12 int n,m,x,y,s,t,d[maxn];
13 struct Edge{
14 Edge *pre;
15 int to,cost;
16 }edge[6000010];
17 Edge *last[maxn],*pt;
18 struct node{
19 int x,d;
20 node(int _x,int _d) : x(_x), d(_d){}
21 inline bool operator < (const node &_Tp) const {
22 return d > _Tp.d;
23 }
24 };
25 priority_queue <node> q;
26 inline int read(){
27 int ans = 0, f = 1; char c = getchar();
28 while (!isdigit(c)){
29 if (c == ‘-‘) f = -1; c = getchar();
30 }
31 while (isdigit(c)){
32 ans = ans * 10 + c - ‘0‘; c = getchar();
33 }
34 return ans * f;
35 }
36 inline void addedge(int x,int y,int z){
37 pt->pre = last[x]; pt->to = y; pt->cost = z; last[x] = pt++;
38 }
39 inline void add(int x,int y,int z){
40 addedge(x,y,z); addedge(y,x,z);
41 }
42 int dijkstra(){
43 clr(d,INF); d[s] = 0; q.push(node(s,0));
44 while (!q.empty()){
45 node now = q.top(); q.pop();
46 if (d[now.x] != now.d) continue;
47 travel(now.x){
48 if (d[p->to] > d[now.x] + p->cost){
49 d[p->to] = d[now.x] + p->cost;
50 q.push(node(p->to,d[p->to]));
51 }
52 }
53 }
54 return d[t];
55 }
56 int main(){
57 n = read(); m = read(); clr(last,0); pt = edge;
58 s = 0; t = (n-1) * (m-1) * 2 + 1;
59 rep(i,0,n-1){
60 rep(j,1,m-1){
61 x = read(); y = ((i*(m-1))<<1)+(j<<1);
62 if (!i) add(j<<1,t,x);
63 else if (i == n-1) add(s,y-((m-1)<<1)-1,x);
64 else add(y,y-((m-1)<<1)-1,x);
65 }
66 }
67 rep(i,0,n-2){
68 rep(j,1,m){
69 x = read(); y = ((i*(m-1))<<1)+(j<<1);
70 if (j == 1) add(s,y-1,x);
71 else if (j == m) add(y-2,t,x);
72 else add(y-2,y-1,x);
73 }
74 }
75 rep(i,0,n-2){
76 rep(j,1,m-1){
77 x = read(); y = ((i*(m-1))<<1)+(j<<1);
78 add(y,y-1,x);
79 }
80 }
81 printf("%d\n",dijkstra());
82 return 0;
83 }