PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000135. Thời điểm màn hình bị hỏng (Monitor)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Thời điểm màn hình bị hỏng (Monitor)

Monitor

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

An n×mn\times m monitor initially has all pixels working. You are given qq pixels: pixel (xi,yi)(x_i,y_i) permanently becomes broken at time tit_i, and each position appears at most once. The monitor is considered broken at the first time any contiguous k×kk\times k block consists entirely of broken pixels. Find that time, or output -1 if this never happens.

Input

The first line contains n,m,k,qn,m,k,q. Each of the next qq lines contains xi,yi,tix_i,y_i,t_i. Row and column indices are 1-based.

Output

Print the earliest failure time, or -1 if the required square never appears.

Subtasks

  • Subtask 1 (20 points): 1≤n≤81\le n\le 8; 1≤m≤81\le m\le 8; $1\le k\le\min(n,m);\ 0\le q\le nm;\ 1\le x_i\le n;\ 1\le y_i\le m;\ 0\le t_i\le10^9$; all pixel coordinates (xi,yi)(x_i,y_i) are distinct.
  • Subtask 2 (30 points): 1≤n≤801\le n\le 80; 1≤m≤801\le m\le 80; $1\le k\le\min(n,m);\ 0\le q\le nm;\ 1\le x_i\le n;\ 1\le y_i\le m;\ 0\le t_i\le10^9$; all pixel coordinates (xi,yi)(x_i,y_i) are distinct.
  • Subtask 3 (50 points): 1≤n≤5001\le n\le 500; 1≤m≤5001\le m\le 500; $1\le k\le\min(n,m);\ 0\le q\le nm;\ 1\le x_i\le n;\ 1\le y_i\le m;\ 0\le t_i\le10^9$; all pixel coordinates (xi,yi)(x_i,y_i) are distinct.

Examples

Input

2 3 2 5
2 1 8
2 2 8
1 2 1
1 3 4
2 3 2

Output

8

Explanation

At time 11, (1,2)(1,2) fails; at time 22, (2,3)(2,3); at time 44, (1,3)(1,3). These do not form a full 2×22\times2 square. At time 88, (2,1)(2,1) and (2,2)(2,2) also fail, so (1,2),(1,3),(2,2),(2,3)(1,2),(1,3),(2,2),(2,3) form a completely broken 2×22\times2 square. None exists before time 88, hence output 8.