#include <bits/stdc++.h>
using namespace std;
long long mod = 1e9 + 7;
int a[503][503];
int c[503][503];
long long t[503][503];
int n, m, k, q;
bool check(long long ti) {
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (c[i][j] && t[i][j] <= ti)
        a[i][j] = 1;
      else
        a[i][j] = 0;
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
    }
  }
  for (int i = 1; i <= n; i++) {
    if (i + k - 1 > n) break;
    for (int j = 1; j <= m; j++) {
      if (j + k - 1 > m) break;
      int x = i + k - 1, y = j + k - 1;
      int res = a[i - 1][j - 1] + a[x][y] - a[i - 1][y] - a[x][j - 1];
      if (res == k * k) return 1;
    }
  }
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  cin >> n >> m >> k >> q;
  while (q--) {
    int i, j, t1;
    cin >> i >> j >> t1;
    c[i][j]++;
    t[i][j] = t1;
  }
  long long l = 0, r = 1e9 + 2;
  long long ans = -1;
  while (l <= r) {
    long long mid = (l + r) / 2;
    if (check(mid))
      r = mid - 1, ans = mid;
    else
      l = mid + 1;
  }
  cout << ans;
}
