#include <bits/stdc++.h>
using namespace std;
const int NIL = -1;
template <class T>
inline T mx(T a, T b) {
  return a > b ? a : b;
}
template <class T>
inline T mi(T a, T b) {
  return a < b ? a : b;
}
template <class T>
inline void sw(T &a, T &b) {
  T t = a;
  a = b;
  b = t;
}
template <class T>
inline T mabs(T x) {
  return x < 0 ? -x : x;
}
inline char gc() {
  char ret;
  while ((ret = getchar()) == ' ' || ret == '\n' || ret == '\t')
    ;
  return ret;
}
const int LIM = 510;
pair<int, int> dat[LIM * LIM];
int bit[LIM][LIM];
int n, m, k, q;
int cur = 0;
inline int mp(int r, int c) { return r * m + c; }
inline int lowbit(int x) { return x & (-x); }
inline void update(int r, int c, int dif) {
  for (int i = r; i <= n; i += lowbit(i))
    for (int j = c; j <= m; j += lowbit(j)) bit[i][j] += dif;
}
inline int query(int r, int c) {
  int ret = 0;
  for (int i = r; i > 0; i -= lowbit(i))
    for (int j = c; j > 0; j -= lowbit(j)) ret += bit[i][j];
  return ret;
}
inline bool check(int x) {
  memset((bit), (0), sizeof(bit));
  for (int i = 0; i < q; i++) {
    if (dat[i].second > x) break;
    update(dat[i].first / m + 1, dat[i].first % m + 1, 1);
  }
  for (int r = k; r <= n; r++)
    for (int c = k; c <= m; c++) {
      int tmp =
          query(r, c) - query(r - k, c) - query(r, c - k) + query(r - k, c - k);
      if (tmp == k * k) return true;
    }
  return false;
}
inline bool cmp(const pair<int, int> &a, const pair<int, int> &b) {
  return a.second < b.second;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL), cout.tie(NULL);
  int x, y;
  cin >> n >> m >> k >> q;
  int r = 0;
  for (int i = 0; i < q; i++) {
    cin >> x >> y >> dat[i].second;
    r = mx(r, dat[i].second);
    dat[i].first = mp(x - 1, y - 1);
  }
  sort(dat, dat + q, cmp);
  int l = 0;
  r++;
  int flag = r;
  while (l < r) {
    int mid = l + ((r - l) >> 1);
    if (check(mid))
      r = mid;
    else
      l = mid + 1;
  }
  cout << (l == flag ? -1 : l);
  return 0;
}
