R3 P3933 Chtholly Nota Seniorious

Keywords: less

This question can be divided into two parts, and then greedy.
Actually, at first I thought about it, but I didn't know how to be greedy. After reading the solution, I suddenly realized it.
When the maximum value is different in the four corners, it should be found from the four corners, then in a ladder shape. The next layer must be less than or equal to the upper one. If the maximum value is in this area, each of the maximum decreases is smaller than the answer. Similarly, the minimum decreases in each area are smaller than the answer. Then the other area will be tested, so one line. Greed in action is OK

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>

#define ll long long
using namespace std;

int n,m,a[5][2200][2200],last[2100],maxn,minn=199999999;
bool ch(int x,int opt){
    if(opt&1) swap(n,m);//The odd number is crossed.
    last[0]=m; 
    for(int i=1;i<=n;i++){
        int j;
        for( j=1;j<=last[i-1];j++)
    if(maxn-a[opt][i][j]>x) break;
        last[i]=j-1;
    }//greedy
    for(int i=1;i<=n;i++){
        int j;
        for( j=last[i]+1;j<=m;j++)
    if(a[opt][i][j]-minn>x) {
        if(opt&1) swap(n,m);return 0;
        }
    }//test

    if(opt&1) swap(n,m);
    return 1;
}
bool check(int x){
    return ch(x,0)||ch(x,1)||ch(x,2)||ch(x,3);//Intersection of four corners
}
int main(){

    scanf("%d%d",&n,&m);
     int x2=n,x3=m,x=1,y=n,y2=m,y3=1;  
    for (int i=1;i<=n;i++){

        for (int j = 1; j <= m; j++){  
            scanf("%d",&a[0][i][j]);
            a[1][x++][y]=a[2][x2][y2--]=a[3][x3--][y3]=a[0][i][j];  
            if (a[0][i][j]>maxn) maxn=a[0][i][j];  
            if (a[0][i][j]<minn) minn=a[0][i][j];  
        }  
        y--; x=1;  
        x2--; y2=m;  
        y3++; x3=m;  } //Input four corners
    int l=0,r=maxn-minn;
    while(l<=r){
        int mid=(l+r)>>1;
        int w=check(mid);
        if(w) r=mid-1;
        else l=mid+1;//Two points answer
    }
    printf("%d",l);
}

Posted by Eamonn on Sat, 09 Feb 2019 06:06:17 -0800