#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
const double EPS = 1e-8;
const int M = 5e2 + 10;
int n, m, k, q;
struct Point {
  int x, y, t;
  bool operator<(const Point &other) const { return t < other.t; }
} a[M * M];
int sum[M][M];
int GetSum(int sx, int sy, int tx, int ty) {
  return sum[tx][ty] - sum[tx][sy - 1] - sum[sx - 1][ty] + sum[sx - 1][sy - 1];
}
bool Broken(int mid) {
  for (int i = 0; i <= n; i++) {
    for (int j = 0; j <= m; j++) {
      sum[i][j] = 0;
    }
  }
  for (int i = 0; i <= mid; i++) {
    sum[a[i].x][a[i].y] = 1;
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      sum[i][j] += sum[i - 1][j];
      sum[i][j] += sum[i][j - 1];
      sum[i][j] -= sum[i - 1][j - 1];
    }
  }
  for (int i = 1; i + k - 1 <= n; i++) {
    for (int j = 1; j + k - 1 <= m; j++) {
      if (GetSum(i, j, i + k - 1, j + k - 1) == k * k) return true;
    }
  }
  return false;
}
int Solve() {
  sort(a, a + q);
  int L = 0, R = q - 1, answer = -1;
  while (L <= R) {
    int mid = (L + R) >> 1;
    if (Broken(mid)) {
      answer = mid;
      R = mid - 1;
    } else {
      L = mid + 1;
    }
  }
  if (answer != -1) answer = a[answer].t;
  return answer;
}
int main() {
  while (~scanf("%d%d%d%d", &n, &m, &k, &q)) {
    for (int i = 0; i < q; i++) {
      scanf("%d%d%d", &a[i].x, &a[i].y, &a[i].t);
    }
    printf("%d\n", Solve());
  }
  return 0;
}
