#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e9 + 10;
const int maxn = 5e2 + 30;
const int maxq = 1e5 + 10;
const int alf = 26;
const long long dlm = 1e9 + 7;
const long long del = 179425601;
const int eps = 1e-7;
string O[] = {"YES", "NO", "Yes", "No"};
vector<pair<int, pair<int, int> > > li;
int n, m, k, q;
int dp[maxn][maxn];
int x[maxn][maxn];
int ch(int v) {
  for (int i = 0; i <= n; i++) {
    for (int j = 0; j <= m; j++) {
      dp[i][j] = 0;
      x[i][j] = 0;
    }
  }
  for (int i = 0; i < li.size(); i++) {
    int ax = li[i].second.first;
    int ay = li[i].second.second;
    if (li[i].first <= v) {
      x[ax][ay] = 1;
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1];
      if (x[i][j] == 1) dp[i][j]++;
    }
  }
  for (int i = k; i <= n; i++) {
    for (int j = k; j <= m; j++) {
      if (dp[i][j] - dp[i - k][j] - dp[i][j - k] + dp[i - k][j - k] == (k * k))
        return 1;
    }
  }
  return 0;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m >> k >> q;
  for (int i = 1; i <= q; i++) {
    int x, y, t;
    cin >> x >> y >> t;
    li.push_back({t, {x, y}});
  }
  sort(li.begin(), li.end());
  int l = 0, r = inf, mid, q = -1;
  while (l <= r) {
    mid = (l + r) / 2;
    if (ch(mid)) {
      q = mid;
      r = mid - 1;
    } else {
      l = mid + 1;
    }
  }
  cout << q;
  return 0;
}
