#include <bits/stdc++.h>
using namespace std;
int n, m, k, q, b[510][510];
struct node {
  int x, y, z;
} a[250010];
bool judge(int p) {
  bool ret = false;
  for (int i = 1; i <= p; i++) b[a[i].x][a[i].y] = 1;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
  for (int i = 1; i <= p; i++)
    ret |= (b[a[i].x][a[i].y] - b[max(a[i].x - k, 0)][a[i].y] -
                b[a[i].x][max(a[i].y - k, 0)] +
                b[max(a[i].x - k, 0)][max(a[i].y - k, 0)] ==
            k * k);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) b[i][j] = 0;
  return ret;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> m >> k >> q;
  for (int i = 1; i <= q; i++) cin >> a[i].x >> a[i].y >> a[i].z;
  sort(a + 1, a + q + 1, [&](node a, node b) { return a.z < b.z; });
  int l = 1, r = q, mid, ans = -1;
  while (l <= r) {
    mid = (l + r) >> 1;
    if (judge(mid))
      ans = mid, r = mid - 1;
    else
      l = mid + 1;
  }
  printf("%d", ans != -1 ? a[ans].z : -1);
  return 0;
}
