#include <bits/stdc++.h>
using namespace std;
const long long modn = 1000000007;
inline long long mod(long long x) { return x % modn; }
struct trip {
  trip(int _x, int _y, int _t) : x(_x), y(_y), t(_t) {}
  int x, y, t;
};
char arr[502][502];
int arrSum[502][502];
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  bool test = false;
  if (test) freopen("/Users/aj/code/HackerRank/input.txt", "r", stdin);
  int n, m, k, q;
  scanf("%d%d%d%d", &n, &m, &k, &q);
  vector<trip> T;
  long long sumRow = 0;
  for (int i = 0; i < q; i++) {
    int x, y, t;
    scanf("%d%d%d", &x, &y, &t);
    T.emplace_back(trip(x, y, t));
  }
  sort(T.begin(), T.end(),
       [](const trip& lhs, const trip& rhs) { return lhs.t < rhs.t; });
  int l = 0, r = T.size();
  int minIdx = -1;
  while (l <= r) {
    int mid = (l + r) / 2;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) arr[i][j] = 0, arrSum[i][j] = 0;
    for (int i = 0; i < mid; i++) arr[T[i].x][T[i].y] = 1;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++)
        arrSum[i][j] = (int)arr[i][j] + arrSum[i - 1][j] + arrSum[i][j - 1] -
                       arrSum[i - 1][j - 1];
    bool found = false;
    for (int i = k; i <= n; i++)
      for (int j = k; j <= m; j++)
        if ((arrSum[i][j] - arrSum[i - k][j] - arrSum[i][j - k] +
             arrSum[i - k][j - k]) == k * k)
          found = true;
    if (found)
      r = mid - 1, minIdx = mid;
    else
      l = mid + 1;
  }
  printf("%d", minIdx != -1 ? T[minIdx - 1].t : -1);
}
