Submission #1236152

#TimeUsernameProblemLanguageResultExecution timeMemory
1236152nasjesThe Kingdom of JOIOI (JOI17_joioi)C++20
100 / 100
2402 ms63508 KiB
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>
#include <set>
#include <queue>
#include <map>
#include <stack>
#include <bitset>
#include <string>
#include <cstring>
#include <iterator>
#include <random>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef long double ld;
const ll dim = 5*1e3+7;
//const ll mod = 1e9 + 7;
const ll inf = 1e18 + 77;
#define endl "\n"
#define fi first
#define pb push_back
#define se second
#define vll vector<ll>

ll n, m;

ll  fl[dim];
ll mx, mn;
ll check(ll val, vector<vll> &a){
    ll mnv=mx-val;
    ll mxv=mn+val;
   // cout<<mnv<<" "<<mxv<<" "<<val<<endl;
    ll can1=1;
    ll can2=1;
    ll end=n+1;
    for(int j=m; j>=1; j--){
        for(int i=1; i<=end; i++){
            if(a[i][j]>mxv){end=i; break;}
        }
        fl[j]=end;
    }
    for(int j=1; j<=m; j++){
        for(int i=n; i>=max(fl[j], 1ll); i--){
            if(a[i][j]<mnv)can1=0;
        }
        for(int i=1; i<fl[j]; i++){
            if(a[i][j]>mxv)can1=0;
        }
        fl[j]=0;
    }

    end=n+1;
    for(int j=1; j<=m; j++){
        for(int i=1; i<=end; i++){
            if(a[i][j]>mxv){end=i; break;}
        }
        fl[j]=end;
    }

    for(int j=1; j<=m; j++){
        for(int i=n; i>=max(fl[j], 1ll); i--){
            if(a[i][j]<mnv)can2=0;
        }
        for(int i=1; i<fl[j]; i++){
            if(a[i][j]>mxv)can2=0;
        }
        fl[j]=0;
    }
    if(can1 || can2)return 1;
    return 0;


}

int main() {
    ll d, k, q, s, t, e, sm;
    cin>>n>>m;
    mx=0;
    mn=inf;
    vector<vll> g(n+5, vll(m+5, 0));
    vector<vll> b(n+5, vll(m+5, 0));

    for(int i=1;i<=n; i++){
        for(int j=1; j<=m; j++){
            cin>>g[i][j];
            mx=max(g[i][j], mx);
            mn=min(g[i][j], mn);
        }
    }
    for(int i=1; i<=n; i++){
        for(int j=1; j<=m; j++){
            b[i][j]=g[n-i+1][j];
        }
    }

    ll l=1;
    ll r=1e9;
    while(r-l>=1){
        ll mid=(l+r)/2;
        if(check(mid, g)|| check(mid, b)){
            r=mid;
        }
        else{
            l=mid+1;
        }
    }
    cout<<l<<endl;


    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...