#include <bits/stdc++.h>
using namespace std;
const int N = 1000;
int pref[N][N];
int cnt[N][N];
vector<tuple<int, int, int> > pix;
int n, m, k, q;
bool check(int x) {
  fill_n(pref[0], N * N, 0);
  fill_n(cnt[0], N * N, 0);
  for (int i = 0; i < x; ++i) {
    ++cnt[get<0>(pix[i])][get<1>(pix[i])];
  }
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      pref[i + 1][j + 1] =
          pref[i][j + 1] + pref[i + 1][j] - pref[i][j] + cnt[i][j];
    }
  }
  for (int i = 0; i + k <= n; ++i) {
    for (int j = 0; j + k <= m; ++j) {
      int s = pref[i + k][j + k] - pref[i][j + k] - pref[i + k][j] + pref[i][j];
      if (s >= k * k) {
        return false;
      }
    }
  }
  return true;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n >> m >> k >> q;
  pix.resize(q);
  for (int i = 0; i < q; ++i) {
    cin >> get<0>(pix[i]) >> get<1>(pix[i]) >> get<2>(pix[i]);
    --get<0>(pix[i]);
    --get<1>(pix[i]);
  }
  sort(pix.begin(), pix.end(),
       [&](const tuple<int, int, int> &a, const tuple<int, int, int> &b) {
         return get<2>(a) < get<2>(b);
       });
  if (check(q)) {
    cout << "-1\n";
    return 0;
  }
  int l = 0, r = q;
  while (r - l > 1) {
    int mid = (l + r) / 2;
    if (check(mid)) {
      l = mid;
    } else {
      r = mid;
    }
  }
  cout << get<2>(pix[r - 1]) << '\n';
  return 0;
}
