#include <bits/stdc++.h>
using namespace std;
const int MAXN = 505;
int N, M, K, Q;
pair<int, pair<int, int> > A[MAXN * MAXN];
int pre[MAXN][MAXN];
bool check(int idx) {
  memset(pre, 0, sizeof(pre));
  for (int i = 0; i <= idx; i++) pre[A[i].second.first][A[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 = K; i <= N; i++)
    for (int j = K; j <= M; j++)
      if (pre[i][j] - pre[i - K][j] - pre[i][j - K] + pre[i - K][j - K] ==
          K * K)
        return true;
  return false;
}
int main() {
  ios::sync_with_stdio(0);
  cin >> N >> M >> K >> Q;
  for (int i = 0; i < Q; i++)
    cin >> A[i].second.first >> A[i].second.second >> A[i].first;
  sort(A, A + Q);
  int lo = 0, hi = Q;
  while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (check(mid))
      hi = mid;
    else
      lo = mid + 1;
  }
  if (lo == Q)
    cout << "-1\n";
  else
    cout << A[lo].first << "\n";
  return 0;
}
