local gx, gy = io.read("*n", "*n") gx, gy = gx + 1, gy + 1 local n, f = io.read("*n", "*n") local len = {} for h = 1, gy do for w = 1, gx do len[(h - 1) * gx + w] = (h + w - 2) * f end end for i = 1, n do local x, y, c = io.read("*n", "*n", "*n") for h = gy - y, 1, -1 do for w = gx - x, 1, -1 do local src = (h - 1) * gx + w local dst = (h - 1 + y) * gx + w + x if len[src] + c < len[dst] then len[dst] = len[src] + c end end end end local ret = (gx + gy - 2) * f for h = 1, gy do for w = 1, gx do ret = math.min(ret, len[(h - 1) * gx + w] + (gy - h + gx - w) * f) end end print(ret)