#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int n, m, k, q, a[N][N], x, y, z, f[N][N];
inline bool check(int tim) {
  for (int i = 1; i <= n; ++i)
    for (int j = m; j; --j) f[i][j] = a[i][j] <= tim ? f[i][j + 1] + 1 : 0;
  for (int i = n; i; --i)
    for (int j = 1; j <= m; ++j) f[i][j] = f[i][j] >= k ? f[i + 1][j] + 1 : 0;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (f[i][j] >= k) return 1;
  return 0;
}
int main() {
  scanf("%d%d%d%d", &n, &m, &k, &q);
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) a[i][j] = 2e9;
  while (q--) scanf("%d%d%d", &x, &y, &z), a[x][y] = z;
  int ans = -1;
  for (int l = 0, r = 1e9, mid; l <= r;
       mid = (l + r) >> 1, check(mid) ? ans = mid, r = mid - 1 : l = mid + 1)
    ;
  printf("%d", ans);
  return 0;
}
