#include <bits/stdc++.h>
using namespace std;
struct node {
  int x, y, t;
} a[500000];
int sum[600][600], flag[600][600];
int n, m, k, q;
bool cmp(node x, node y) { return x.t < y.t; }
bool check(int x) {
  memset(flag, 0, sizeof(flag));
  for (int i = 1; i <= x; i++) flag[a[i].x][a[i].y] = 1;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      sum[i][j] =
          sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + flag[i][j];
  for (int i = 1; i <= n - k + 1; i++)
    for (int j = 1; j <= m - k + 1; j++) {
      int li = i, lj = j, ri = i + k - 1, rj = j + k - 1;
      int xx =
          sum[ri][rj] - sum[li - 1][rj] - sum[ri][lj - 1] + sum[li - 1][lj - 1];
      if (xx == k * k) return 1;
    }
  return 0;
}
int bs(int l, int r) {
  if (l == r) return l;
  int mid = (l + r) >> 1;
  if (check(mid))
    return bs(l, mid);
  else
    return bs(mid + 1, r);
}
int main() {
  scanf("%d%d%d%d", &n, &m, &k, &q);
  for (int i = 1; i <= q; i++) scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].t);
  if (!q) {
    if (k == 0)
      puts("0");
    else
      puts("-1");
    return 0;
  }
  sort(a + 1, a + 1 + q, cmp);
  int ans = bs(1, q);
  if (check(ans))
    printf("%d\n", a[ans].t);
  else
    puts("-1");
  return 0;
}
