#include using namespace std; using ll = long long; template using rpriority_queue = priority_queue, greater>; template istream& operator >> (istream& is, vector& vec) { for(T& x : vec) is >> x; return is; } template ostream& operator << (ostream& os, const vector& vec) { if(vec.empty()) return os; os << vec[0]; for(auto it = vec.begin(); ++it != vec.end(); ) os << ' ' << *it; return os; } /*int main(){ ios::sync_with_stdio(false); cin.tie(0); int h, w, k, t; cin >> h >> w >> k >> t; if(t >= h + w){ cout << 0 << '\n'; return 0; } vector> C(h, vector(w)), D(h, vector(w)); for(int i = 0; i < k; i++){ int y, x, v1, v2; cin >> y >> x >> v1 >> v2; y--, x--; C[y][x] = v1; D[y][x] = v2; } const ll INF = 1ll << 60; //時間, y, x vector>> dptb(h + w, vector>(h, vector(w, INF))); vector>> pqtb(h + w); dptb[0][0][0] = 0; pqtb[0].emplace(0, 0, 0); ll ans = INF; for(int hv = 0; hv < h + w; hv++){ auto &pq = pqtb[hv]; auto &dp = dptb[hv]; while(!pq.empty()){ ll d; int y, x; tie(d, y, x) = pq.top(); pq.pop(); if(d > dp[y][x]) continue; if(C[y][x] && hv + D[y][x] < h + w){ int hv2 = hv + D[y][x]; if(d - C[y][x] + 1 <= dptb[hv2][y][x]){ dptb[hv2][y][x] = d - C[y][x] + 1; pqtb[hv2].emplace(dptb[hv2][y][x], y, x); } } for(int i = 0; i < 4; i++){ int ny = y + (i == 0) - (i == 1); int nx = x + (i == 2) - (i == 3); if(ny < 0 || nx < 0 || ny >= h || nx >= w) continue; if(d + 1 >= dp[ny][nx]) continue; dp[ny][nx] = d + 1; pq.emplace(d + 1, ny, nx); } } for(int y = 0; y < h; y++){ cerr << dp[y] << '\n'; } cerr << '\n'; if(dp[h - 1][w - 1] <= t){ cout << hv << '\n'; return 0; } } cout << -1 << '\n'; }*/ int main(){ ios::sync_with_stdio(false); cin.tie(0); int h, w, k, t; cin >> h >> w >> k >> t; if(t >= h + w - 2){ cout << 0 << '\n'; return 0; } vector> C(h, vector(w)), D(h, vector(w)); for(int i = 0; i < k; i++){ int y, x, v1, v2; cin >> y >> x >> v1 >> v2; y--, x--; C[y][x] = v1; D[y][x] = v2; } int dec = h + w - 2 - t; const ll INF = 1ll << 60; //時間, y, x = 疲労 vector>> dp(dec, vector>(h, vector(w, INF))); rpriority_queue> pq; dp[0][0][0] = 0; pq.emplace(0, 0, 0, 0); ll ans = INF; while(!pq.empty()){ ll tim, d; int y, x; tie(d, tim, y, x) = pq.top(); pq.pop(); if(d > dp[tim][y][x]) continue; if(C[y][x] >= 2){ int nt = tim + C[y][x] - 1; if(nt < dec){ if(d + D[y][x] < dp[nt][y][x]){ dp[nt][y][x] = d + D[y][x]; pq.emplace(dp[nt][y][x], nt, y, x); } }else{ ans = min(ans, d + D[y][x]); } } for(int i = 0; i < 4; i++){ int ny = y + (i == 0) - (i == 1); int nx = x + (i == 2) - (i == 3); if(ny < 0 || nx < 0 || ny >= h || nx >= w) continue; if(ny < y || nx < x){ int nt = tim - 2; if(nt < 0) continue; if(d >= dp[nt][ny][nx]) continue; dp[nt][ny][nx] = d; pq.emplace(d, nt, ny, nx); }else{ if(d >= dp[tim][ny][nx]) continue; dp[tim][ny][nx] = d; pq.emplace(d, tim, ny, nx); } } } if(ans == INF) ans = -1; cout << ans << '\n'; }