1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| #include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f #define LC(x) (x<<1) #define RC(x) ((x<<1)+1) #define MID(x,y) ((x+y)>>1) #define all(a) (a).begin(),(a).end() #define CLR(arr,val) memset(arr,val,sizeof(arr)) #define FAST_IO ios::sync_with_stdio(false);cin.tie(0); typedef pair<int, int> pii; typedef long long LL; const double PI = acos(-1.0); const int N = 2000010; struct edge { int to, nxt, w; edge() {} edge(int _to, int _nxt, int _w): to(_to), nxt(_nxt), w(_w) {} } E[N * 4]; int head[N], tot, d[N], vis[N];
void init() { CLR(head, -1); tot = 0; } void add(int s, int t, int w) { E[tot] = edge(t, head[s], w); head[s] = tot++; E[tot] = edge(s, head[t], w); head[t] = tot++; } int spfa(int s, int t) { deque<int>Q; CLR(d, 0x3f); vis[s] = 1; d[s] = 0; Q.push_back(s); while (!Q.empty()) { int u = Q.front(); Q.pop_front(); vis[u] = 0; for (int i = head[u]; ~i; i = E[i].nxt) { int v = E[i].to; if (d[v] > d[u] + E[i].w) { d[v] = d[u] + E[i].w; if (!vis[v] && d[v] <= d[t]) { vis[v] = 1; if (!Q.empty() && d[v] < d[Q.front()]) Q.push_front(v); else Q.push_back(v); } } } } return d[t]; } int main(void) { int n, m, i, j, w; while (~scanf("%d%d", &n, &m)) { if (n == 1 && m == 1) { puts("0"); continue; } init(); int S = 0, T = (n - 1) * (m - 1) * 2 + 1; for (j = 1; j < m; ++j) { scanf("%d", &w); add(j, T, w); } for (i = 2; i <= n - 1; ++i) { for (j = 1; j < m; ++j) { scanf("%d", &w); add((2 * i - 3) * (m - 1) + j, 2 * (i - 1) * (m - 1) + j, w); } } for (j = 1; j < m; ++j) { scanf("%d", &w); add((2 * n - 3) * (m - 1) + j, S, w); } for (i = 1; i <= n - 1; ++i) { for (j = 1; j <= m; ++j) { scanf("%d", &w); if (j == 1) { add((2 * i - 1) * (m - 1) + j, S, w); } else if (j == m) { add((2 * (i - 1)) * (m - 1) + j - 1, T, w); } else { add(2 * (i - 1) * (m - 1) + j - 1, 2 * (i - 1) * (m - 1) + j - 1 + m, w); } } } for (i = 1; i <= n - 1; ++i) { for (j = 1; j <= m - 1; ++j) { scanf("%d", &w); add((i - 1) * (m - 1) * 2 + j, (i - 1) * (m - 1) * 2 + j + m - 1, w); } } printf("%d\n", spfa(S, T)); } return 0; }
|