#include <bits/stdc++.h>
using namespace std;
int n, m, k, q;
pair<int, pair<int, int>> que[500 * 500];
int grid[509][509];
bool is_ok(int time) {
  memset(grid, 0, sizeof grid);
  int idx = 0;
  while (idx < q && que[idx].first <= time) {
    int i = que[idx].second.first;
    int j = que[idx].second.second;
    grid[i][j] = 1;
    idx++;
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      grid[i][j] += grid[i][j - 1] + grid[i - 1][j] - grid[i - 1][j - 1];
    }
  }
  int nk = n - k + 1, mk = m - k + 1;
  for (int i = 1; i <= nk; i++) {
    for (int j = 1; j <= mk; j++) {
      int sum = grid[i + k - 1][j + k - 1] - grid[i + k - 1][j - 1] -
                grid[i - 1][j + k - 1] + grid[i - 1][j - 1];
      if (sum == k * k) return true;
    }
  }
  return false;
}
void testCase() {
  cin >> n >> m >> k >> q;
  for (int i = 0; i < q; ++i) {
    cin >> que[i].second.first >> que[i].second.second >> que[i].first;
  }
  sort(que, que + q);
  int l = 0, r = que[q - 1].first;
  int ans = -1;
  while (l <= r) {
    int mid = l + (r - l) / 2;
    if (is_ok(mid)) {
      ans = mid;
      r = mid - 1;
    } else
      l = mid + 1;
  }
  cout << ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  testCase();
  return 0;
}
