/* -*- coding: utf-8 -*- * * 2695.cc: No.2695 Warp Zone - yukicoder */ #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 1000; const int MAX_GN = MAX_N * 2 + 2; const long long LINF = 1LL << 62; /* typedef */ typedef long long ll; typedef pair pii; typedef pair pli; typedef vector vpii; /* global variables */ int xs[MAX_GN], ys[MAX_GN]; vpii nbrs[MAX_GN]; ll ds[MAX_GN]; /* subroutines */ inline int dist(int i, int j) { return abs(xs[j] - xs[i]) + abs(ys[j] - ys[i]); } /* main */ int main() { int h, w, n; scanf("%d%d%d", &h, &w, &n); for (int i = 0; i < n; i++) scanf("%d%d%d%d", xs + i, ys + i, xs + n + i, ys + n + i); int st = n * 2, gl = st + 1, gn = gl + 1; xs[st] = 1, ys[st] = 1; xs[gl] = h, ys[gl] = w; nbrs[st].push_back({gl, dist(st, gl)}); for (int i = 0; i < n; i++) { nbrs[st].push_back({i, dist(st, i)}); nbrs[n + i].push_back({gl, dist(n + i, gl)}); nbrs[i].push_back({n + i, 1}); for (int j = 0; j < n; j++) nbrs[n + i].push_back({j, dist(n + i, j)}); } fill(ds, ds + gn, LINF); ds[st] = 0; priority_queue q; q.push({0, st}); while (! q.empty()) { auto [ud, u] = q.top(); q.pop(); ud = -ud; if (ds[u] != ud) continue; if (u == gl) break; for (auto [v, w]: nbrs[u]) { ll vd = ud + w; if (ds[v] > vd) { ds[v] = vd; q.push({-vd, v}); } } } printf("%lld\n", ds[gl]); return 0; }