Recently Luba bought a monitor. Monitor is a rectangular matrix of size n × m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k × k consisting entirely of broken pixels. She knows that q pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all q pixels stopped working).
Input
The first line contains four integer numbers n, m, k, q (1 ≤ n, m ≤ 500, 1 ≤ k ≤ min(n, m), 0 ≤ q ≤ n·m) — the length and width of the monitor, the size of a rectangle such that the monitor is broken if there is a broken rectangle with this size, and the number of broken pixels.
Each of next q lines contain three integer numbers xi, yi, ti (1 ≤ xi ≤ n, 1 ≤ yi ≤ m, 0 ≤ t ≤ 109) — coordinates of i-th broken pixel (its row and column in matrix) and the moment it stopped working. Each pixel is listed at most once.
We consider that pixel is already broken at moment ti.
Output
Print one number — the minimum moment the monitor became broken, or "-1" if it's still not broken after these q pixels stopped working.
Examples
Input
2 3 2 5
2 1 8
2 2 8
1 2 1
1 3 4
2 3 2
Output
8
Input
3 3 2 5
1 2 2
2 2 1
2 3 5
3 2 10
2 1 100
Output
-1
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve problem: given n x m grid, initially all pixels are working. At certain times t_i, specific pixels (x_i, y_i) become broken (permanently). We need to find the earliest time T such that there exists a square submatrix of size k x k (contiguous rows and columns) where all pixels are broken (i.e., the set of broken pixels at time T includes that whole square). If never, output -1.
Constraints: n,m ≤ 500, k ≤ min(n,m), q up to n*m (so up to 250k). Each pixel appears at most once. Times up to 1e9.
We need to find the minimum time T such that there is a k x k all-broken block.
This is a classic problem that can be solved by binary searching on T and checking if at time T there is a k x k all-broken square. For a given time T, we consider all pixels with t_i ≤ T as broken, others as working. Then we need to check existence of a k x k all-broken square. That can be done by building a binary matrix (1 for broken) and computing for each cell whether it is the bottom-right corner of a k x k all-1 square, using prefix sums or sliding window. Complexity O(nm) per check, total O(nm log MAX_T). But q can be up to 250k, and nm up to 250k, so that's okay: 500500=250k. Log(1e9)~30, so about 7.5 million operations, fine.
But we can do better perhaps by not scanning entire grid each check if we only have q entries? However scanning whole grid (250k) 30 times is 7.5M, which is fine.
But we need to output minimum time T among times when the condition becomes true. Since events are at discrete times (the given times), the answer is one of the times t_i (or -1). Actually it could be some time between? Because pixels break at given times; at time exactly t_i, the pixel becomes broken. So the condition becomes true exactly at some time t_i (or later) when enough broken pixels accumulate. But the answer is the moment when it first becomes broken. Since it changes only at times t_i, we can sort events by time and process incrementally, check after each event? That would be O(q * k^2) naive. But we could use a data structure to maintain the existence of a k x k block. Since n,m up to 500, we could maybe update and check quickly after each event? However q up to 250k, worst-case n*m, we could simply binary search on time.
But note: binary search on time T and then building the binary matrix from scratch each time would require iterating over all q pixels to set broken ones with t_i <= T. Since q up to 250k and log factor ~30, that's 7.5M, fine. However building the matrix of size nm (250k) each check also 250k. So total ~15M per check? Actually we need to set up the matrix: initialize all zeros, then for each pixel with t_i <= T set to 1. That is O(q) per check (or O(nm) if we fill with zeros, but we can allocate matrix and fill with zeros each time? That's extra O(nm) per check. So per check O(nm + q) = O(nm) since q ≤ nm. So about 250k * 30 = 7.5M to fill zeros? Actually we can reuse matrix and only update? Not necessary, 7.5M operations is fine.
But careful: nm could be 500500=250,000, and we have up to 30 checks, so 7.5 million operations for zeroing each time, plus scanning for prefix sums, also similar. That's fine in C++.
But we need to be careful with time: 7.5M * constant is small.
Alternatively, we could sort events by time and use a binary search on the sorted list of distinct times. Since answer must be one of the times (or -1). So we can binary search on index in sorted times. That yields O(log q) checks. Still similar.
Edge case: If the condition is already true at time 0? But all pixels initially working, so no. So answer -1 if never.
Thus solution: read all queries. Store them: (x,y,t). Sort by t? We need to binary search on time T, so we need to be able to quickly get all pixels with t <= T. For each check, we could iterate over all q pixels and mark if t <= T. That's O(q) per check. Since q up to 250k, and 30 checks -> 7.5M, fine. Alternatively, we can sort events by t and then for each check we can process events up to some index. But easier: just for each check loop over all q and if t <= T set grid[x][y]=1. That's simple.
But we must also handle the grid dimension indexing. Since n,m up to 500, we can use 2D array.
Algorithm:
Read n,m,k,q.
Create array of triple (x,y,t) size q.
Store all.
If q < k*k? Actually not necessary, but quick early -1? Could be but we still have to check.
Let times = sorted list of unique t_i (or just use binary search on time value).
We need to find minimum T such that condition holds. We can binary search on T in the range [min_t, max_t] (or 0 to 1e9). However condition is monotonic: if it's true at T, it remains true for any larger T (since more pixels become broken). So binary search works.
But we must be careful: the answer might be a time that is not exactly one of the t_i? Suppose at time T1 condition becomes true because pixel broken exactly at T1, but there might be T between T1-1 and T1? Not relevant, we need the moment it becomes broken. Since pixel breaks at exact t_i, the condition can only become true exactly at some t_i. So if we binary search on integer time, we might find a time that is not a t_i but condition is true; then we need to find the earliest t_i where it becomes true. But since condition monotonic, the earliest time when it's true is the min t_i such that condition holds at t_i. So we could binary search on the sorted list of t_i. Or after binary searching we can then find the exact t_i by scanning? Simpler: collect all distinct times, sort them, then binary search on the index. That way we get the exact time.
Implementation:
Extract all times into array times[].
Sort times.
Then binary search low=0, high=len(times)-1 (or use while low<high) to find smallest index such that condition holds at T = times[mid]. But careful: it's possible that condition never holds even at max time; in that case answer -1.
After binary search, we check if condition holds at times[high]? Actually typical: we want first index where condition true. We can set lo = -1, hi = len(times)-1? Or use lower_bound style: lo = 0, hi = len; while lo < hi: mid = (lo+hi)//2; if check(times[mid]): hi = mid else lo = mid+1. Then if after loop check(times[lo]) is true, answer times[lo]; else -1.
But we must also consider if condition might become true at a time that is not exactly any t_i? No, because pixels only break at given times. At time T, the set of broken pixels is exactly those with t_i <= T. So the condition changes only at times when a pixel breaks. So earliest T where condition is true must be one of the t_i (or possibly exactly 0? No). So using sorted times works.
However what about if condition becomes true exactly at time T which is not in the list because multiple pixels have same T? Actually T is in the list because at least one pixel with that time contributed. But if condition becomes true because multiple pixels with same time, the exact moment they all break? The problem states: "We consider that pixel is already broken at moment ti." So at moment ti, the pixel becomes broken instantaneously. So if multiple pixels have same ti, they all become broken at that same moment. So condition may become true at that moment. So T must be equal to some ti. So good.
But what if the condition becomes true after all pixels have broken, but the max time is not among times? Actually max time is among times. So fine.
Now, we need to implement check(T). Steps:
Create a 2D array broken of size (n+1) x (m+1) initialized to 0 (using int or bool).
For each pixel in list: if t <= T: broken[x][y] = 1.
Then compute 2D prefix sum of broken to answer submatrix sum quickly. Or we can use sliding window on rows and columns to compute existence of k x k all ones more efficiently without prefix sum? Prefix sum is fine.
Compute prefix sum ps[i][j] = number of broken in rows 1..i, cols 1..j. Standard: ps[i][j] = broken[i][j] + ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1].
Then for each possible top-left corner (i, j) with i from 1 to n-k+1, j from 1 to m-k+1, compute sum of submatrix from (i,j) to (i+k-1, j+k-1) = ps[i+k-1][j+k-1] - ps[i-1][j+k-1] - ps[i+k-1][j-1] + ps[i-1][j-1]. If that equals k*k, then there is a full broken square. Return true.
If none, return false.
Complexities: O(n*m + q) per check.
But note: In check we need to loop over all q to set broken. However we can also build broken in O(q) and then compute prefix sum O(nm). Since nm could be larger than q? But both up to 250k. So total per check O(nm + q) = O(nm) since q ≤ n*m. So that's fine.
Alternative: Because we are doing binary search, we might want to avoid reinitializing the whole nm grid each time to zeros, because that adds O(nm) per check. However we can allocate a static 2D array and for each check we need to reset only positions we set? But we set broken based on current T, and we need to set 1 for those with t<=T. We could have an array with time values per pixel? But since we need to compute prefix sum each time, we might as well rebuild from scratch. It's acceptable.
But we can also do the following: sort events by time, and for binary search we need to quickly get the set of broken pixels up to a certain index. We can pre-sort events by t and then for each check we take events up to index mid (where mid is based on sorted times). But we still need to set broken for those events and maybe unset? Since binary search indices are different each time, we cannot easily reuse without rebuilding. But we can use a persistent data structure? Not needed.
Given constraints, straightforward approach will pass.
Edge Cases:
k=1: Then condition is there exists any broken pixel. The answer is the smallest t_i. Binary search will find it.
q=0: Then answer -1. Check function always false. So binary search will result -1.
Potential Pitfall: n,m up to 500, so ps array dimension (501,501). Use int.
Implementation Steps:
Read n,m,k,q.
Create vector<tuple<int,int,int>> pixels (or three arrays).
Also collect all times in a vector times.
If q==0: output -1 and exit.
Sort times.
If check(times.back()) is false: output -1.
Else binary search for smallest index where check true.
Print times[lo].
But we must also consider the possibility that condition becomes true at time t that is not the maximum but there are many times. Works.
Now implement check(T):
Allocate int grid[n+1][m+1] = {0}. But to avoid large stack for 2D array, we can use vector<vector> or a flat vector.
For each pixel: if t <= T: grid[x][y] = 1.
Compute prefix sums similarly on grid. We'll use ps array of same dimensions.
Then loop i from k to n: actually we need to consider top-left row from 1 to n-k+1, but easier: for i from k to n: for j from k to m: check square ending at (i,j). If sum == kk -> return true. Compute sum using ps[i][j] - ps[i-k][j] - ps[i][j-k] + ps[i-k][j-k]. Note: careful with indices: we defined ps with rows 1..n, columns 1..m. So check for i from k to n, j from k to m: if sum of square of size k with bottom-right (i,j) is kk, then return true.
Return false.
Potential optimization: if number of broken pixels is less than k*k, we can quickly return false. But not needed.
Now the binary search on times: we need to map each T to an index in sorted times. Since times may have duplicates, but it's fine.
Better: we can binary search directly on time values from 0 to 1e9, and after finding the minimal T, we need to output T. However, that T might not be exactly equal to a t_i; but since the condition is monotonic and changes only at t_i, the minimal T that satisfies condition will be equal to the smallest t_i for which condition holds. But if we binary search on integer values, we might get some value T that is not a t_i, but condition holds; then we need to find the smallest t_i >= T? Actually if condition holds at T, then it also holds at any later time. The earliest time when it becomes true is some t_i. So if we binary search for the minimal integer T (not necessarily a t_i) such that condition holds, that minimal integer T will be the smallest t_i that satisfies condition because condition is false for T-1. But we must ensure that T-1 is integer. Since t_i are integers, the condition at T-1 is false if T is the minimal integer satisfying. That T must be some t_i. However, consider scenario where condition becomes true at t=5, but we test T=6, condition true, but minimal integer T satisfying might be 5 because condition also true at 5. If we binary search correctly, we should get 5. Since binary search on continuous integers yields the smallest integer satisfying predicate. That should be the exact t_i (since predicate changes only at integer times when t_i occur). But careful: times can be large up to 1e9, but binary search on [0, 1e9] takes about 30 steps. That is also fine. Then we don't need to sort times. Simpler: binary search on integer T directly.
But need to guarantee that the predicate is monotonic and correct at all integer T. Since pixels break at integer times t_i, at T < t_i pixel not broken; at T >= t_i broken. So predicate is monotonic non-decreasing: if it's true at T, it's true for any T' > T. So binary search works.
We need to implement predicate check(T) as described.
Potential issue: T may be less than any t_i, then predicate false. Good.
Binary search:
Let lo = 0, hi = 1e9 (or maybe max_t). Since answer could be up to 1e9. Or we can set hi = max(t_i) because if not satisfied at max(t_i) then -1. But we can set hi = 1e9 and after binary search check if predicate(hi) true. However we need to know if it's ever true. So we can compute max_t = max(t_i), then set hi = max_t. Because if it's not true at max_t, it's never true. Actually if predicate at max_t false, then answer -1. So we can set hi = max_t. Then binary search on [0, max_t] inclusive.
But careful: if max_t = 0? But q>0 ensures max_t at least 0. If q=0, we already handle.
Implementation:
int lo = 0, hi = max_t; ans = -1;
while (lo <= hi) {
int mid = (lo+hi)/2;
if (check(mid)) {
ans = mid;
hi = mid-1;
} else {
lo = mid+1;
}
}
print ans; // -1 if never true.
But note: if predicate false at max_t, ans remains -1.
Now, check(mid) will be called many times. We'll implement it efficiently.
Potential optimization: since n,m ≤ 500, we can allocate global arrays and reuse them. For each check, we need to fill grid with zeros. Instead of using vector<vector> and initializing all to zero each time (which is O(nm)), we can use an integer "timestamp" technique: have a 2D array val[n+1][m+1] and a corresponding 2D array lastMark[n+1][m+1] that stores the last time we set the pixel to broken in the current check. But simpler: just use vector and assign all to 0. O(250k30) = 7.5M assignments, fine. Actually 250k * 30 = 7.5M, each assignment maybe 4 bytes, 30 million bytes, trivial.
But we also have to loop over q (up to 250k) each check to set grid to 1. That's another 7.5M operations. So total about 15M per check? Actually 250k for grid init, plus 250k for scanning q, plus computing prefix sums and scanning for squares. So per check maybe about 1e6 operations, times 30 = 30 million, still fine.
But we also have to compute prefix sums: that is nm operations (250k) plus scanning squares (nm). So maybe up to 750k per check? Actually compute prefix sums: iterate over all cells (n+1)(m+1) ~ 250k, plus scanning squares ~ (n-k+1)(m-k+1) up to 250k. So total ~ 750k per check. Times 30 ~ 22.5M. All combined still well within time limit (typical 2 sec, C++ can handle).
We can further reduce by precomputing sorted list of pixels by time, and for each binary search iteration we can reuse the grid by only updating based on a threshold index. But not needed.
Thus implement.
Edge Cases: We need to be careful about 1-indexed grid. Input coordinates are 1-based.
Implementation details:
Read n,m,k,q.
vector x(q), y(q), t(q).
int max_t = 0;
For i in 0..q-1: read x[i], y[i], t[i]; max_t = max(max_t, t[i]);
If q == 0: print -1 and return.
Define a function bool check(int T) that uses global n,m,k,q, and the arrays x,y,t.
Inside check:
code
// allocate grid and ps as vectors of vectors int with dimensions (n+1, m+1)
vector<vector<int>> grid(n+1, vector<int>(m+1, 0));
for (int i=0; i<q; ++i) {
if (t[i] <= T) {
grid[x[i]][y[i]] = 1;
}
}
// prefix sum
vector<vector<int>> ps(n+1, vector<int>(m+1, 0));
for (int i=1; i<=n; ++i) {
for (int j=1; j<=m; ++j) {
ps[i][j] = grid[i][j] + ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1];
}
}
// check for kxk square
for (int i=k; i<=n; ++i) {
for (int j=k; j<=m; ++j) {
int sum = ps[i][j] - ps[i-k][j] - ps[i][j-k] + ps[i-k][j-k];
if (sum == k*k) return true;
}
}
return false;
Potential optimization: early break after true.
Memory: grid and ps each about (501*501) ints, ~1 MB each, okay.
But we are creating these vectors inside check, which will be allocated and deallocated many times. That could be heavy. But 30 allocations of 2 * 250k ints ~ 21e64 bytes = 8 MB per call? Actually each vector allocation might be expensive. To avoid overhead, we can allocate global arrays and reuse, but we need to zero them each time. Let's consider performance: 30 times allocating vector of size ~250k is not huge, but might be okay. However to be safe, we can allocate static arrays (like int grid[501][501]) global and then inside check we zero them using loops. Since size fixed, that's fast.
Better: use global arrays and memset? But memset on 2D array of 501x501 = 251001 ints, 1 MB, that's fine. But we can't memset int array to zero quickly? Use fill_n? We'll just use nested loops to set to 0. That is 250k assignments.
But note: we also need prefix sum array. We can compute prefix sum in place? Not exactly. We could compute a 2D prefix sum directly on grid by accumulating rows and columns? We could use grid as the prefix sum after transformation. Typically we compute prefix sum in separate array to not overwrite. But we could reuse grid as the prefix sum after computing, but then we lose original broken flags. But we don't need them later. So we could compute prefix sum in place: first convert grid into its own prefix sum. But careful: we need original grid to compute prefix sum. However we can compute prefix sum in same array by first making each row cumulative then cumulative columns? That would also work: we can compute row-wise cumulative sums then column-wise to get 2D prefix sum. But we must be careful that the intermediate steps are correct. However we can just have two separate arrays: grid and ps. Or we can compute prefix sum on the fly without storing original grid: we can build ps directly: we need broken values. Instead of first storing grid and then computing ps, we can compute ps by accumulating. But we need to know broken for each cell. So we could have a bool array broken, and then compute ps in a separate array. The memory usage is not a problem.
Simplify: Use global arrays broken[501][501] and ps[501][501] as int (or short). Inside check, we zero both.
Option: Use int broken[501][501] = {0}; but we need to reset each call. Use loops.
Let's outline using global arrays:
const int MAXN = 501;
int n, m, k, q;
int x[250000], y[250000], t[250000];
int broken[MAXN][MAXN];
int ps[MAXN][MAXN];
bool check(int T) {
// reset broken to 0
for (int i=1; i<=n; ++i) {
for (int j=1; j<=m; ++j) {
broken[i][j] = 0;
}
}
// mark broken
for (int i=0; i<q; ++i) {
if (t[i] <= T) {
broken[ x[i] ][ y[i] ] = 1;
}
}
// compute prefix sum
for (int i=1; i<=n; ++i) {
for (int j=1; j<=m; ++j) {
ps[i][j] = broken[i][j] + ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1];
}
}
// check squares
for (int i=k; i<=n; ++i) {
for (int j=k; j<=m; ++j) {
int sum = ps[i][j] - ps[i-k][j] - ps[i][j-k] + ps[i-k][j-k];
if (sum == k*k) return true;
}
}
return false;
}
That's fine.
But we can also optimize by not resetting broken entire grid each time if we only set necessary cells from scratch; but we need to zero out cells that were set in previous check. Since we are overwriting all cells that become broken (based on T) with 1, but cells not broken may still be 1 from previous check. So we need to reset all to 0 before marking. So yes.
But we could use a timestamp technique: maintain a 2D array lastUpdated with version number, and a global currentVersion. Then for each check, increment version. For each pixel with t<=T, set broken[x][y] = currentVersion. Then when checking squares, we need to know if a cell is broken; we compare broken[x][y] == currentVersion. This avoids resetting entire grid. For computing prefix sum, we need numeric values 0/1; we can compute on the fly? But we can still compute ps using the version approach: we need to know if cell is broken (1) or not (0) during the prefix sum. We can fill a temporary array? Or we could compute prefix sum by iterating over all cells, and set value = 1 if broken matches currentVersion else 0. That would still require scanning all cells to compute ps, which is O(nm) anyway, but we avoid resetting the array, which is also O(nm). So it's similar.
But we also need to mark broken cells from the list. We can combine: we can first set broken array to 0 by resetting? Actually scanning all cells to compute ps already loops over all cells. So we could reuse that to also compute the prefix sum, but we need to know which cells are broken. If we have the broken array with version, we can for each cell check if it's set in this version. However that would involve a check for each cell: if (broken[i][j] == curVer) then 1 else 0. That is similar cost to resetting an array of ints. But resetting requires writing to each cell (set to 0). That is also a write. So it's about the same.
Given simplicity, I'll go with resetting.
But we can also avoid separate broken array entirely by directly building prefix sum using the list of broken pixels? Perhaps we could use a difference array approach? But we need to answer many queries of existence of kxk square. There is known technique using sliding window maximum? But not needed.
Thus final solution: binary search T, check with prefix sums.
But we should consider early exit: if number of broken pixels with t <= T is less than k*k, then condition false. We can quickly compute count. Could precompute sorted times and prefix counts? But not needed.
Sorted times: 1,2,4,8,8. Condition true at T=8? At T=8, all broken? Let's check: at T=8, all pixels are broken? List: all have t <=8. So broken: (2,1),(2,2),(1,2),(1,3),(2,3). Visual: rows 1-2, cols 1-3:
Now 2x2 squares: top-left (1,1): cells (1,1),(1,2),(2,1),(2,2) => (1,1) not broken => false. (1,2): cells (1,2),(1,3),(2,2),(2,3) => all broken? (1,2) broken, (1,3) broken, (2,2) broken, (2,3) broken => yes. So true at T=8. At T=4: broken: times <=4: (2,1?8>4 no), (2,2?8>4 no), (1,2?1<=4 yes), (1,3?4<=4 yes), (2,3?2<=4 yes). So broken: (1,2),(1,3),(2,3). Then 2x2? (1,2) requires (1,2),(1,3),(2,2),(2,3) but (2,2) missing. (1,1) missing (1,1). So false. At T=2: broken: (1,2) t=1; (2,3) t=2; (1,3?) t=4 >2 no; others >2. So only two broken, false. So minimal T=8. Our binary search should find 8.
Example 2:
3 3 2 5
1 2 2
2 2 1
2 3 5
3 2 10
2 1 100
Max_t = 100. Condition? At T=100, all broken? Let's list: (1,2),(2,2),(2,3),(3,2),(2,1). Broken: positions: (1,2), (2,1), (2,2), (2,3), (3,2). Check 2x2 squares: possible top-left: (1,1): cells (1,1),(1,2),(2,1),(2,2) => (1,1) missing. (1,2): (1,2),(1,3),(2,2),(2,3) => (1,3) missing. (2,1): (2,1),(2,2),(3,1),(3,2) => (3,1) missing. (2,2): (2,2),(2,3),(3,2),(3,3) => (3,3) missing. So false. So answer -1.
Our binary search would check T from 0 to 100; if at max_t false, answer remains -1.
Works.
Now implement.
Potential pitfalls: memory/time: we have to reset broken and ps each call. Use nested loops over n*m. That's fine.
But we can micro-opt: since n,m <= 500, we can use static arrays and reset with memset? Using memset on a 2D array of size 501x501 int (about 1,002,001 bytes) would be okay per call. But careful: memset works on bytes, and setting to 0 works for int if it's 0. So we could do:
int broken[501][501];
memset(broken, 0, sizeof(broken));
But we also need ps. We can also memset ps to 0. However, note that ps is computed later, we don't need to reset it before use because we overwrite all entries in the loops from i=1..n, j=1..m. But we also use ps[i-1][j] etc. So we need to have ps[0][] and ps[][0] as zero. So we should ensure those are zero. They are already zero if we set the whole array to zero, or we can rely on the loops to set them but they are outside loops. So it's easier to just zero the whole ps array (or just the rows 0 and columns 0) but easiest: allocate as global static (outside function) which is zero-initialized by default? Global arrays are zero-initialized. But then we need to reset only the part we modify? Actually we modify broken when we set to 1 for each pixel; we also need to reset broken to 0 before marking. Since broken is global and we may have previous marks, we need to clear the portion we will use (rows 1..n, cols 1..m). If we use memset on broken, that sets whole array to 0, but then we need to also clear ps? For ps, we will compute new values, but we must ensure that the regions outside the computed area (like indices > n or > m) are not used, but we only access up to n,m. So we can simply compute ps for i=1..n, j=1..m. We don't need to reset ps because we overwrite all those entries. However ps[i][j] depends on ps[i-1][j] and ps[i][j-1], which for i=1 or j=1 access ps[0][j] or ps[i][0] which are always zero if the whole array was initially zero and never changed. Since they are global, they remain zero. So we can skip resetting ps. But if we don't reset ps, previous values in indices up to n,m might remain from previous check? But we are overwriting them in the loop. For each i,j we assign ps[i][j] = ... So they are overwritten. So no need to reset. But careful: The loop goes over i=1..n, j=1..m, and assigns each element. So previous values are overwritten. So we don't need to clear ps. Good.
Thus only broken array needs to be cleared before each check. So we can do:
memset(broken, 0, sizeof(broken));
But broken is int array, and memset sets each byte to 0. Works because 0 int is all bytes zero. However sizeof(broken) = 501501sizeof(int) = about 1e6 bytes? Actually 501*501 ≈ 251,001, times 4 = 1,004,004 bytes, about 1MB. memset 1MB 30 times = 30 MB writes, fine.
Alternatively, we could loop over q and set broken[x][y]=0? Not enough because we need to clear all cells, not only those that were set. So memset is easiest.
But we also need to clear broken for the rows and columns that we will use? Actually after memset, entire array is 0, fine.
We also need to consider that we are using global arrays of fixed size 501, but n,m up to 500, so indices 1..500, fine.
Now the marking: for each pixel with t <= T, set broken[x][y] = 1.
Now compute prefix sum in ps. We can compute in the same array broken? Let's see: we could compute prefix sum in broken itself, but then we lose original broken markers? We don't need them after we compute prefix sum. So we could compute prefix sum in place: after marking broken, we can transform broken to prefix sum. That saves one array. But careful: to compute 2D prefix sum in place, we can do:
for i from 1..n:
for j from 1..m:
broken[i][j] += broken[i-1][j] + broken[i][j-1] - broken[i-1][j-1];
But that's exactly ps. Then later we check squares using this. So we don't need separate ps. So we can just use broken as the prefix sum array. That reduces memory and we don't need to reset ps.
But then after we compute prefix sum, we no longer have the original binary broken values. But that's okay because we only need prefix sums. However we must be careful: The original broken array after marking is 0/1. Then we transform to prefix sums. So after each check, we need to reset broken to all zeros for next check. But we can still use broken for prefix sum. So we can have a single array grid that we clear, mark, then convert to prefix sum. That works.
But note: In the prefix sum transformation, we need to use the values from previous rows/columns. Since we are overwriting in place, we must ensure that the original value is used correctly. The formula: grid[i][j] = grid[i][j] + grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1] works if grid[i][j] currently holds the original value (0 or 1). Since we haven't modified those yet, it's fine. And we update row by row, column by column; the values of grid[i-1][j], grid[i][j-1], grid[i-1][j-1] are already the prefix sums for those positions if we proceed in increasing i and j. So it works.
Thus we can use a single grid array.
Now we also need to handle base cases: grid[0][] and grid[][0] must be 0. Since we cleared entire array with memset, they are zero. Good.
Now algorithm for check:
bool check(int T) {
// clear grid
memset(grid, 0, sizeof(grid)); // but careful: grid size is 501x501 = 251001 ints, ~1MB
// mark broken pixels
for (int i=0; i<q; ++i) {
if (t[i] <= T) {
grid[ x[i] ][ y[i] ] = 1;
}
}
// compute prefix sum in place
for (int i=1; i<=n; ++i) {
for (int j=1; j<=m; ++j) {
grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];
}
}
// check for kxk squares
for (int i=k; i<=n; ++i) {
for (int j=k; j<=m; ++j) {
int sum = grid[i][j] - grid[i-k][j] - grid[i][j-k] + grid[i-k][j-k];
if (sum == k*k) return true;
}
}
return false;
}
But note: after we compute prefix sum, the values in grid[i][j] are prefix sums, which can be up to i*j. That's fine.
Now, we must be cautious about the use of memset on a large array each check. 30 * 1MB = 30 MB writes, fine.
Now about reading input: q can be 0, then we should output -1 directly. Also if check(max_t) false then output -1.
Now, binary search boundaries: lo = 0, hi = max_t. But we need to consider if condition can be true at time 0? No, because initially no broken pixels, so check(0) false unless k=0? k>=1, so false. So lo can be 0. But if q=0, we early exit.
Now implement.
Potential improvement: we can early exit check if number of broken pixels < kk. We can count them while marking: count if t<=T. If count < kk, return false without computing prefix sum. This might save time for early T's. Since we are doing binary search, many mid values might be small. So it's beneficial. We'll add that.
Thus in check, after marking, we can maintain a counter of broken cells. But careful: if we mark by setting grid[x][y]=1, we can increment a counter. However we may mark the same pixel multiple times? No, each pixel appears at most once. So we can count unique pixels with t<=T. So we can compute count in loop. Then if count < k*k, return false.
But note: we need to still set grid for marking? Actually we still need grid for prefix sum if count >= k*k. So we need to set grid anyway. So we can count while marking.
Now check function:
int cnt = 0;
for each pixel: if t<=T: grid[x][y]=1, cnt++;
if cnt < k*k: return false;
Then compute prefix sums and check squares.
Now, in marking we set grid[x][y] to 1. But we also need to ensure that we don't double count? Each pixel appears at most once.
Now about binary search: we want minimal T such that check(T) true. Use while lo<=hi.
Pseudo:
int solve() {
if (q == 0) return -1;
int lo = 0, hi = max_t, ans = -1;
while (lo <= hi) {
int mid = lo + (hi-lo)/2;
if (check(mid)) {
ans = mid;
hi = mid-1;
} else {
lo = mid+1;
}
}
return ans;
}
But we need to ensure that if check(max_t) false, ans remains -1. That's fine.
But note: It is possible that condition becomes true at time t that is not equal to any integer? Actually times are integers, so okay.
Potential overflow: t up to 1e9, so int is fine.
Now about performance: In each check we call memset on grid which is size 501x501=251001 ints = about 1,004,004 bytes. 30 times -> about 30 MB of writes, plus loops over q (250k) 30 times -> 7.5M, plus prefix sum loops 30250k=7.5M, plus checking squares ~30250k=7.5M. So total operations around 22.5M, plus some overhead. Should run easily within 1 second? Possibly, but need to be careful with memory and speed in C++. 30 * (2250k) loops = 15M, plus memset 301MB = 30MB writes, but memset is fast. So total time maybe less than 0.2 sec? Actually 30 * (250k) ~ 7.5M operations for marking; each operation is simple. So it's fine.
But we could also use binary search on sorted times to reduce number of checks to log q (maybe up to 18) instead of log 1e9 (30). But it's similar.
One more nuance: In some cases, answer could be 0? For k=0? but k>=1, so no.
Edge case: q may be less than kk, then answer -1. But our binary search will eventually check max_t and return false, ans=-1. However we can early return -1 if q < kk. But not necessary.
But be careful: the grid size is up to 500, but the maximum number of pixels is n*m which can be 250k, and q can be that many. So storing x,y,t in arrays of size 250k is fine.
Now test with examples.
Example 1:
n=2,m=3,k=2,q=5, times: 8,8,1,4,2. max_t=8.
Check(4) should false, check(8) true. Binary search: lo=0,hi=8,mid=4 false => lo=5,mid=6? Actually mid=6? Let's simulate: lo=0,hi=8,mid=4 false => lo=5,hi=8,mid=6 (or 5+8//2=6) -> check(6) false? Pixels with t<=6: t=1,2,4? 8's not included, so broken: (1,2),(1,3)?? Wait (1,3) t=4, (2,3) t=2, (1,2) t=1. Others t=8 >6. So still only 3 broken. So false => lo=7,hi=8,mid=7 -> check(7) false (still 8's not included) => lo=8,hi=8,mid=8 true => ans=8, hi=7, loop ends. So ans=8.
Example 2: max_t=100, check(100) false, ans remains -1.
Now what about scenario where some pixel times are large and we binary search on [0, max_t]? That's fine.
But we need to consider that check(T) may be called with T that is not among the given times; but it's okay because condition depends on t_i <= T.
Now, we might optimize by early exit in check after finding a square. That's done.
Now, memory: grid[501][501] static global. We'll define as int grid[505][505] to be safe.
But note: In compute prefix sum, we use indices up to n and m. With n,m up to 500, we access grid[i-k][j-k]; i-k can be 0, j-k can be 0, which are fine if grid[0][] and grid[][0] are defined and zeroed.
Now, possible issue: we use memset on grid, but grid is int array; memset sets bytes, so if we set all bytes to 0, each int becomes 0. That's fine. However after we compute prefix sums, we don't need to zero grid again for next call because we will memset again. So it's fine.
But we must also set grid[0][] and grid[][0] to 0 each time because we memset entire grid, so they are zero. Good.
Now, we also need to handle that n,m may be less than 500, so we don't need to clear entire grid, only up to n,m. But memset whole grid is fine.
One more optimization: Instead of resetting entire grid, we could only reset the cells we changed. Since we only mark at most q cells per check, and we need to clear them for next check. But we also need to clear cells that were set previously from other pixels. However since we set only the cells corresponding to pixels with t <= T, there might be many cells left as 0. But after marking, grid contains 1's at some positions. In next check with a different T, we need to have grid cleared to 0 before marking new set. So we need to reset those 1's back to 0. If we only reset the positions we previously marked, we would need to keep track of which positions we set, which adds complexity. Given the size, memset is simpler.
Now, we also need to consider that q can be large (250k) and we loop over all q each check. That's fine.
Now, we must be careful about indexing: x[i], y[i] are 1-indexed, so we can directly use them.
Now, edge case: n or m may be 0? No, n,m >=1.
Now, let's implement.
Potential pitfalls: The binary search high bound: if condition never true, we output -1. Our while loop sets ans only if check true. So ans stays -1.
But we might also want to handle scenario where max_t is -1 if q=0. Already handled.
Now, what about scenario where k > n or k > m? But problem says k ≤ min(n,m), so fine.
Now, we also should check performance on worst-case: n=500,m=500,k=1,q=250000 all distinct. Then each check will mark up to all pixels (if T large). That's 250k markings. Then prefix sum loops over 250k cells. So about 500k operations per check. 30 checks = 15M, fine.
Now, we might consider using bitset? Not needed.
Now, we should also consider that input times can be up to 1e9, so binary search on integer range is safe.
Now, I think solution is solid.
However, there might be a more efficient approach: offline processing with a segment tree or something? But not needed.
Now, we need to produce final answer.
Let's code.
Implementation steps:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 502; // just to be safe, use 502
int n, m, k, q;
int xs[250005], ys[250005], ts[250005];
int grid[MAXN][MAXN];
bool check(int T) {
memset(grid, 0, sizeof(grid));
int cnt = 0;
for (int i = 0; i < q; ++i) {
if (ts[i] <= T) {
grid[xs[i]][ys[i]] = 1;
++cnt;
}
}
if (cnt < kk) return false;
// compute prefix sums in place
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
grid[i][j] += grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1];
}
}
// check kxk squares
for (int i = k; i <= n; ++i) {
for (int j = k; j <= m; ++j) {
int sum = grid[i][j] - grid[i-k][j] - grid[i][j-k] + grid[i-k][j-k];
if (sum == kk) return true;
}
}
return false;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n >> m >> k >> q;
int max_t = 0;
for (int i = 0; i < q; ++i) {
cin >> xs[i] >> ys[i] >> ts[i];
max_t = max(max_t, ts[i]);
}
if (q == 0) {
cout << "-1\n";
return 0;
}
int lo = 0, hi = max_t, ans = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (check(mid)) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
cout << ans << "\n";
return 0;
}
But we must be careful: grid is defined as [MAXN][MAXN], and memset uses sizeof(grid). sizeof(grid) = MAXNMAXNsizeof(int). MAXN=502 => 5025024 = about 1,008,016 bytes, still fine.
But we need to set MAXN to maybe 505 to be safe. But 501 is enough (since n,m <=500). So we can set const int N = 501; (but include index 0). Actually need N=501, but if we define grid[501][501], indices from 0 to 500, n up to 500, okay. But 501x501 = 251001, we need to ensure loops go up to n,m inclusive. So N=501.
Better to use:
const int MAXN = 500 + 5;
So MAXN=505.
Now, one nuance: In check, we use memset on grid. But grid may be large; we should ensure that grid is defined globally so it's zero-initialized at start. That's fine.
But we call check many times, each time we memset the entire grid. That includes rows/cols up to MAXN-1, even though we only need up to n,m. But that's okay.
But we also need to ensure that grid indices for rows/columns up to n and m are cleared, but we also clear beyond n,m; no harm.
Now, time: 30 * memset of ~1MB = 30 MB; loops over q 30 times = 7.5M; loops over n*m 30 times = 7.5M; total fine.
But we can also reduce number of checks by binary searching on sorted distinct times; that would be at most log2(q) <= 18. But not needed.
Now, we need to test with sample.
Let's manually run sample 1 with code.
But ensure that for k=2, k*k = 4, and sum == 4 works.
Now, potential bug: If kk is large (k up to 500, kk up to 250,000) which fits in int.
Now, confirm that prefix sum computation: grid[i][j] after transformation holds prefix sum up to (i,j). The original 0/1 values are overwritten. That's fine.
Now, edge: When we compute sum for kxk square, we use grid[i][j] - grid[i-k][j] - grid[i][j-k] + grid[i-k][j-k]. Since grid[i][j] is prefix sum, it includes all cells from (1,1) to (i,j). So the sum of square with top-left (i-k+1, j-k+1) to (i,j) is that expression. It works.
Now, test with a case where k=1: then we check for i=1..n, j=1..m: sum = grid[i][j] - grid[i-1][j] - grid[i][j-1] + grid[i-1][j-1] = original broken value at (i,j). So if any broken, return true. Good.
Now, about early count condition: cnt < kk returns false. That is correct because we need at least kk broken pixels to have a full square. That can skip prefix sum computation for many checks. Good.
Now, possible integer overflow? grid prefix sum can be up to total number of broken pixels <= n*m <= 250k, which fits in int.
Now, confirm that we are using int for grid but after prefix sum grid values can be up to 250k, still fits.
Now, complexity wise, fine.
Now, we might think about using bitset to accelerate? Not needed.
Now, we also need to consider if q is very large but many pixels have same coordinates? Problem says each pixel is listed at most once. So fine.
Now, we might want to handle cases where n or m is less than k? But k ≤ min(n,m), so fine.
Now, final code.
But there's one nuance: In check, after we compute prefix sum, we loop over all i from k to n, j from k to m. That's (n-k+1)*(m-k+1) which could be up to 250k. Good.
Now, one more optimization: after we find a square, we can break loops. We'll just return true.
Now, edge case: k could be 0? Not possible.
Now, we also need to consider if max_t = 0? Then hi=0, binary search with mid=0. check(0) will likely be false unless there are pixels with t=0? Possibly there could be pixels with t=0 (since t can be 0). So if t=0 pixel exists and condition holds at T=0, then answer 0. But check(0) should be true only if enough pixels with t<=0, i.e., t=0, to form square. So it's possible. Our binary search handles lo=0, hi=0, mid=0, check(0) returns true? If true, ans=0, hi=-1, loop ends, answer 0. Good.
Now, final code.
But we have to be careful: the arrays xs, ys, ts are of size q (max 250000). So we need to allocate dynamically or static with maximum size. Since q can be up to n*m = 250000, we can define arrays of size 250000+5.
Alternatively, we can use vector. But global arrays are fine.
But we have to read q. If q=0, early exit.
Now, one more thought: We might want to pre-sort pixels by time to reduce work per check? Actually we loop over all q each check, which is fine. But we could also binary search on the sorted times and only consider first mid pixels, but then we need to sort and maybe handle marking only up to index. However, if we binary search on time directly, each check we still have to loop over all q. That's okay.
But what about the case q = n*m = 250k and we do about 30 checks -> 7.5M loops, okay.
Now, I'll produce final solution.
But we must test performance: 7.5M loops, each with simple comparison and assignment. Should be okay.
Now, we need to be careful about using memset inside check: grid is int array, but we are using it to store prefix sums which can be up to 250k. The next check we memset to zero again. That's fine.
But note: In check, we also compute prefix sum. If we return early due to cnt < k*k, we don't compute prefix sum, but we still need to clear grid for next check? Actually we called memset at start, so grid is cleared. Then we set some ones. If we return false early, the grid remains with some ones, but it's a local array? No, it's global. But we memset at start of each check, so each check starts with grid zeroed. So early return doesn't matter because next check will memset again.
But what about caching? Not an issue.
Now, consider if q is large and we have many checks, the memset may become a bottleneck but still fine.
Now, I'll provide final answer.
But there is also a known solution using sliding window maximum of time values? Actually we could also compute for each possible kxk square the maximum time