#include <bits/stdc++.h>
using namespace std;
const int N = 1e9;
pair<int, pair<int, int>> p[250000];
int n, m, k, q;
int a[501][501], pre[501][501];
bool check(int mid) {
  memset(pre, 0, sizeof pre);
  for (int i = 0; p[i].first <= mid && i < q; i++) {
    pre[p[i].second.first][p[i].second.second] = 1;
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      pre[i][j] += pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1];
    }
  }
  for (int i = 1; i + k - 1 <= n; i++) {
    for (int j = 1; j + k - 1 <= m; j++) {
      if (pre[i + k - 1][j + k - 1] - pre[i + k - 1][j - 1] -
              pre[i - 1][j + k - 1] + pre[i - 1][j - 1] ==
          k * k)
        return true;
    }
  }
  return false;
}
int main() {
  scanf("%d %d %d %d", &n, &m, &k, &q);
  for (int i = 0; i < q; i++) {
    scanf("%d%d%d", &p[i].second.first, &p[i].second.second, &p[i].first);
  }
  sort(p, p + q);
  int l = 0, r = 1e9, mid, ans = -1;
  while (l <= r) {
    mid = (l + r) / 2;
    if (check(mid)) {
      ans = mid;
      r = mid - 1;
    } else
      l = mid + 1;
  }
  printf("%d\n", ans);
  return 0;
}
