#line 2 "kyopro_lib/template/template.hpp" #include using namespace std; using ll = long long; #define all(x) (x).begin(), (x).end() template ostream &operator<<(ostream &os, const pair &p) { os << p.first << " " << p.second; return os; } ll sum(vector a){ ll res = 0; for(auto x:a) res += x; return res; } template istream &operator>>(istream &is, pair &p) { is >> p.first >> p.second; return is; } template ostream &operator<<(ostream &os, const vector &v) { ll s = (ll)v.size(); for (ll i = 0; i < s; i++) os << (i ? " " : "") << v[i]; return os; } template istream &operator>>(istream &is, vector &v) { for (auto &x : v) is >> x; return is; } #define rep(i, n) for (ll (i) = 0; (i) < (ll)(n); (i)++) #line 2 "main.cpp" signed main(){ ll H,W,N; cin >> H >> W >> N; H--;W--; map,ll> mp; priority_queue,pair>>, vector,pair>>>, greater,pair>>>> q; rep(i,N) { ll a,b,c,d; cin >> a >> b >> c >> d; a--;b--;c--;d--; q.push({min(a+b,c+d),{{a,b},{c,d}}}); } ll finaly = H+W; while(!q.empty()) { auto [_,p] = q.top(); q.pop(); if (mp[p.first] == 0 and mp[p.second] == 0) continue; auto [a,b] = p.first; auto [c,d] = p.second; if (mp[{a,b}] == 0) { mp[{a,b}] = a+b; for(auto x:mp) { if (x.second != 0) { mp[{a,b}] = min(mp[{x.first.first,x.first.second}]+abs(a+b-x.first.first-x.first.second),mp[{a,b}]); } } }else { mp[{a,b}] = min(a+b,mp[{a,b}]); for(auto x:mp) { if (x.second != 0) { mp[{a,b}] = min(mp[{x.first.first,x.first.second}]+abs(a+b-x.first.first-x.first.second),mp[{a,b}]); } } } if (mp[{c,d}] == 0) { mp[{c,d}] = min(c+d,mp[{a,b}]+1); for(auto x:mp) { if (x.second != 0) { mp[{c,d}] = min(mp[{x.first.first,x.first.second}]+abs(c+d-x.first.first-x.first.second),mp[{c,d}]); } } }else { mp[{c,d}] = min(c+d,min(mp[{c,d}],mp[{a,b}]+1)); for(auto x:mp) { if (x.second != 0) { mp[{c,d}] = min(mp[{x.first.first,x.first.second}]+abs(c+d-x.first.first-x.first.second),mp[{c,d}]); } } } finaly = min(finaly,H+W-c-d+mp[{c,d}]); finaly = min(finaly,H+W-a-b+mp[{a,b}]); } cout << finaly << endl; }