Monitor CodeForces - 846D ——二维前缀和

Recently Luba bought a monitor. Mon

itor 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 × kconsisting 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.

意思是求m*n中某k*k块的显示屏全部都坏了的话该显示屏就坏了,求屏幕坏的t。

求k*k坏了可以用二位前缀和类似求面积的方法来

二维前缀和 https://blog.csdn.net/yzyyylx/article/details/78298318

因为时间是一直增加,可以二分时间求最小时间

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=505;
struct node
{
    int x,y,t;
}s[500005];
int a[maxn][maxn],b[maxn][maxn];
int n,m,k,q;
bool cmp(node a,node b)
{
    return a.t<b.t;
}
int check(int t)//这里就表示二分的时间t时刻
{
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    for(int i=1;i<=t;i++)
        a[s[i].x][s[i].y]=1;
    for(int i=1;i<=n;i++)//二位前缀和处理
    for(int j=1;j<=m;j++)
    {
        b[i][j]=b[i-1][j]+b[i][j-1]-b[i-1][j-1]+a[i][j];
    }
    for(int i=k;i<=n;i++)//遍历看是否成立
    for(int j=k;j<=m;j++)
    {
        if(b[i][j]+b[i-k][j-k]-b[i-k][j]-b[i][j-k]==k*k)
            return 1;
    }
    return 0;
}
int main()
{
    int i,j;
    while(cin>>n>>m>>k>>q)
    {
        for(i=1;i<=q;i++)
            cin>>s[i].x>>s[i].y>>s[i].t;
        sort(s+1,s+1+q,cmp);
        int l=1,r=q;
        int ans=-1;
        while(l<=r)
        {
            int mid=(l+r)/2;
            if(check(mid))
            {
                ans=s[mid].t;
                r=mid-1;
            }
            else
                l=mid+1;
        }
        printf("%d\n",ans);
    }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/swust5120171204/article/details/85385232