1 #include<bits/stdc++.h>
2 #define CLR(a, b) memset((a), (b), sizeof((a)))
3 using namespace std;
4 const int INF = 1e9+5;
5 const int N = 2e6+5;
6 const int M = 3*N;
7 int head[N];
8 int d[N], vis[N];
9 struct Edge{
10 int v, c, nex;
11 }E[M];
12 int num = 0;
13 void add(int u,int v,int c){
14 E[num].v = v; E[num].c = c; E[num].nex = head[u];
15 head[u] = num++;
16 }
17 struct qnode{
18 int v,c,x;
19 qnode(int _v=0,int _c=0,int _x=0):v(_v),c(_c),x(_x){}
20 bool operator < (const qnode &r)const{
21 return r.c<c;
22 }
23 };
24 void dij(int s, int n) {//起点、终点
25 CLR(vis, 0);
26 for(int i = 0; i <= n; i++) d[i] = INF;
27 priority_queue<qnode>q;
28 while(!q.empty()) q.pop();
29 d[s] = 0;
30 q.push(qnode(s, 0));
31 qnode t;
32 while(!q.empty()) {
33 t = q.top(); q.pop();
34 int u = t.v;
35 if(vis[u])continue;
36 vis[u] = true;
37 for(int i = head[u]; ~i; i = E[i].nex) {
38 int v = E[i].v;
39 int c = E[i].c;
40 if(!vis[v] && d[v] > d[u] + c) {
41 d[v] = d[u] + c;
42 q.push(qnode(v, d[v]));
43 }
44 }
45 }
46 }
47 int main() {
48 int n, m;
49 int k, i, j, u, v, w;
50 CLR(head,-1); CLR(E, 0);
51
52 scanf("%d%d", &n, &m);
53 int s = 0; //起点
54 int t = 2*(n-1)*(m-1)+1;//终点
55
56 for(i = 1; i <= n; ++i) {
57 for(j = 1; j < m; ++j) {
58 scanf("%d", &w);
59 u = ( i==1? s : (2*(i-1)-1)*(m-1)+j );
60 v = ( i==n? t : 2*(i-1)*(m-1)+j );
61 add(u, v, w); add(v, u, w);
62 }
63 }
64 for(i = 1; i < n; ++i) {
65 for(j = 1; j <= m; ++j) {
66 scanf("%d", &w);
67 u = ( j==m? s : 2*(i-1)*(m-1)+j-1+m );
68 v = ( j==1? t : 2*(i-1)*(m-1)+j-1 );
69 add(u, v, w); add(v, u, w);
70 }
71 }
72 for(i = 1; i < n; ++i) {
73 for(j = 1; j < m; ++j) {
74 scanf("%d", &w);
75 u = 2*(i-1)*(m-1)+j;
76 v = (2*(i-1)+1)*(m-1)+j;
77 add(u, v, w); add(v, u, w);
78 }
79 }
80
81 dij(s, t);
82 printf("%d\n", d[t]);
83 return 0;
84 }