#include <bits/stdc++.h>
using namespace std;
long long mon[501][501], n, m, k;
vector<pair<long long, pair<long long, long long>>> a;
bool comp(const pair<long long, pair<long long, long long>> &g,
          const pair<long long, pair<long long, long long>> &h) {
  return g.first < h.first;
}
bool broken(long long d) {
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      mon[i][j] = 0;
    }
  }
  for (auto p : a) {
    long long u = p.first, x = p.second.first, y = p.second.second;
    if (u > d) break;
    mon[x][y] = 1;
  }
  long long ver[n + 1][m + 1];
  for (int i = 0; i <= n; i++) ver[i][0] = 0;
  for (int i = 0; i <= m; i++) ver[0][i] = 0;
  for (int i = 1; i <= m; i++) {
    ver[0][i] = 0;
    for (int j = 1; j <= n; j++) ver[j][i] = ver[j - 1][i] + mon[j][i];
  }
  long long sum = 0;
  for (int i = 1; i <= n - k + 1; i++) {
    sum = 0;
    for (int x = 1; x <= k; x++) sum += ver[i + k - 1][x] - ver[i - 1][x];
    if (sum >= k * k) return true;
    for (int j = k + 1; j <= m; j++) {
      sum += ver[i + k - 1][j] - ver[i - 1][j];
      sum -= (ver[i + k - 1][j - k] - ver[i - 1][j - k]);
      if (sum >= k * k) return true;
    }
  }
  return false;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int q;
  cin >> n >> m >> k >> q;
  while (q--) {
    int x, y, t;
    cin >> x >> y >> t;
    a.push_back({t, {x, y}});
  }
  sort(a.begin(), a.end(), comp);
  long long l = 0, r = 1e16;
  while (l < r) {
    long long f = (l + r) / 2;
    if (broken(f))
      r = f;
    else
      l = f + 1;
  }
  if (l == 1e16)
    cout << -1;
  else
    cout << l << endl;
}
