import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } enum INF = 10L^^18; enum DX = [+1, 0, -1, 0]; enum DY = [0, +1, 0, -1]; void main() { try { for (; ; ) { const M = readInt; const N = readInt; const K = readInt; const T = readLong; auto A = new int[K]; auto B = new int[K]; auto C = new int[K]; auto D = new long[K]; foreach (k; 0 .. K) { A[k] = readInt - 1; B[k] = readInt - 1; C[k] = readInt; D[k] = readLong; } auto ids = new int[][](M, N); foreach (x; 0 .. M) ids[x][] = -1; foreach (k; 0 .. K) { ids[A[k]][B[k]] = k; } const limT = 2 * (M + N) + 5; alias Entry = Tuple!(long, "c", int, "x", int, "y", int, "t"); BinaryHeap!(Array!Entry, "a.c > b.c") que; auto dist = new long[][][](M, N, limT); foreach (x; 0 .. M) foreach (y; 0 .. N) dist[x][y][] = INF; dist[0][0][M + N] = 0; que.insert(Entry(0, 0, 0, M + N)); for (; !que.empty; ) { const c = que.front.c; const x = que.front.x; const y = que.front.y; const t = que.front.t; que.removeFront; if (dist[x][y][t] == c) { void update(long cc, int xx, int yy, int tt) { chmax(tt, 0); if (tt < limT) { if (chmin(dist[xx][yy][tt], cc)) { que.insert(Entry(cc, xx, yy, tt)); } } } foreach (dir; 0 .. 4) { const xx = x + DX[dir]; const yy = y + DY[dir]; if (0 <= xx && xx < M && 0 <= yy && yy < N) { update(c, xx, yy, t + 1); } } const k = ids[x][y]; if (~k) { update(c + D[k], x, y, t - C[k] + 1); } } } long ans = INF; foreach (t; 0 .. limT) if (t <= M + N + T) { chmin(ans, dist[M - 1][N - 1][t]); } writeln((ans >= INF) ? -1 : ans); } } catch (EOFException e) { } }