#include #ifdef LOCAL #include "./debug.cpp" #else #define debug(...) #define print_line #endif using namespace std; using ll = long long; template vector dijkstra(const vector>> &G, int start = 0) { int n = G.size(); vector dst(n, numeric_limits::max()); priority_queue> pq; dst[start] = 0; pq.push(make_pair(0, start)); while (!pq.empty()) { auto [dst_sum, now] = pq.top(); pq.pop(); dst_sum = -dst_sum; if (dst[now] < dst_sum) continue; for (auto [nxt, cost] : G[now]) { if (dst[nxt] > dst[now] + cost) { dst[nxt] = dst[now] + cost; pq.push(make_pair(-dst[nxt], nxt)); } } } return dst; } int main() { int H, W, N; cin >> H >> W >> N; vector> E(N); for (int i = 0; i < N; i++) { for (int j = 0; j < 4; j++) { cin >> E[i][j]; E[i][j]--; } } vector>> G(2 * N + 2); for (int i = 0; i < N; i++) { for (int j = 0; j < 4; j++) { G[2 * N].push_back({2 * i, E[i][0] + E[i][1]}); G[2 * i].push_back({2 * N, E[i][0] + E[i][1]}); G[2 * N + 1].push_back({2 * i, H - E[i][0] + W - E[i][1] - 2}); G[2 * i].push_back({2 * N + 1, H - E[i][0] + W - E[i][1] - 2}); G[2 * N].push_back({2 * i + 1, E[i][2] + E[i][3]}); G[2 * i + 1].push_back({2 * N, E[i][2] + E[i][3]}); G[2 * N + 1].push_back({2 * i + 1, H - E[i][2] + W - E[i][3] - 2}); G[2 * i + 1].push_back({2 * N + 1, H - E[i][2] + W - E[i][3] - 2}); G[2 * i].push_back({2 * i + 1, 1}); } } G[2 * N].push_back({2 * N + 1, H + W - 2}); G[2 * N + 1].push_back({2 * N, H + W - 2}); vector dst = dijkstra(G, 2 * N); cout << dst[2 * N + 1] << endl; }