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).
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.
Print one number — the minimum moment the monitor became broken, or "-1" if it's still not broken after these q pixels stopped working.
2 3 2 5 2 1 8 2 2 8 1 2 1 1 3 4 2 3 2
8
3 3 2 5 1 2 2 2 2 1 2 3 5 3 2 10 2 1 100
-1
void presolve() {
for(int i = 1; i <= n; i++) {
LL line = 0;
for(int j = 1; j <= m; j++) {
line += A[i][j];
pre[i][j] = pre[i - 1][j] + line;
}
}
}
修改:初始值为0的情况,第一次做二维前缀得到当前位置的值,第二次做前缀得到前缀和
A[x1][y1]+=d,A[x2+1][y1]-=d,A[x1][y2+1]-=d,A[x2+1][y2+1]+=d A[x1][y1]+=d,A[x2+1][y1]−=d,A[x1][y2+1]−=d,A[x2+1][y2+1]+=d
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<sstream>
#include<map>
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e9+1;
int n,m,q;
int k;
int mp[505][505];
struct node
{
int x,y;
int t;
}E[505*505];
int cmp(node a,node b)
{
return a.t<b.t;
}
int ok(int x)
{
for(int i = 0;i<=n;i++){
for(int j = 0;j<=m;j++)
mp[i][j] = 0;
}
for(int i = 0;i<q;i++){
if(E[i].t>x){
break;
}
mp[E[i].x][E[i].y] = 1;
}
for(int i = 1;i<=n;i++){
int line = 0;
for(int j = 1;j<=m;j++){
line += mp[i][j];
mp[i][j] = mp[i-1][j]+line;
}
}
int falg = 0;
for(int i = 1;i<=n;i++){
for(int j = 1;j<=m;j++){
int x2 = i+k-1;
int y2 = j+k-1;
if(x2>n||y2>m) continue;
if(mp[x2][y2]-mp[x2][j-1]-mp[i-1][y2]+mp[i-1][j-1]==k*k)
{
falg = 1;
break;
}
}
if(falg)
break;
}
return falg;
}
int main()
{
while(~scanf("%d%d%d%d",&n,&m,&k,&q))
{
for(int i = 0;i<q;i++){
scanf("%d%d%d",&E[i].x,&E[i].y,&E[i].t);
}
sort(E,E+q,cmp);
int l = 0;
int r = maxn;
while(r-l>1){
int mid = (l+r)/2;
if(ok(mid)){
r = mid;
}
else{
l = mid;
}
}
if(ok(0)){
r= 0;
}
if(r >= maxn){
puts("-1");
}
else cout<<r<<endl;
}
}