D. Monitor
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
题目大意:
有一个
N×M
的矩阵,给你
Q
个位置坏的时间,如果有一个
解题思路:
首先我们可以二分答案,对于一次cheak,由于我们要找检查
K×K
的子矩阵,我们可以先把时间小于等于二分值的位置制
1
,然后求二维前缀和,枚举右下角用二维前缀和检查即可。
总时间复杂度
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#define INF 0x3f3f3f3f3f3f3f3f
#define LL long long
const int MAXN=500+3;
const int MAXT=1000000000;
int N, M, K, Q;
int y[MAXN*MAXN], x[MAXN*MAXN], t[MAXN*MAXN];
int sum[MAXN][MAXN];
bool judge(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<Q;++i)
if(t[i]<=mid)
sum[y[i]][x[i]]=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-1]-sum[i-1][j-1];
if(i>=K && j>=K && sum[i][j]-sum[i-K][j]-sum[i][j-K]+sum[i-K][j-K]==K*K)
return true;
}
return false;
}
int main()
{
scanf("%d%d%d%d", &N, &M, &K, &Q);
for(int i=0;i<Q;++i)
scanf("%d%d%d", &y[i], &x[i], &t[i]);
int l=-1, r=MAXT+1;
while(r-l>1)
{
int mid=(l+r)>>1;
if(judge(mid))
r=mid;
else l=mid;
}
printf("%d\n", r==MAXT+1?-1:r);
return 0;
}