Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- //numbers
- using ll=long long;
- #define int ll
- //std data structure
- #define all(x) begin(x), end(x)
- #define sz(x) (int) (x).size()
- //vectors
- #define V vector
- #define vi V<int>
- #define v2i V<vi>
- #define v3i V<v2i>
- #define vpi V<pi>
- #define vsi V<si>
- #define vb V<bool>
- #define pb push_back
- //constants
- const int INF=922337203685477580;
- int h,w;
- v2i arr;
- v2i adj;
- int smin=INF;
- bool verif(int k) {
- int h=sz(arr);
- int w=sz(arr[0]);
- vi bds(h+1,w);
- for (int i=0; i<h; i++) {
- bds[i+1]=bds[i];
- for (int j=0; j<bds[i]; j++) {
- if (arr[i][j]>smin+k) {
- bds[i+1]=j-1; break;
- }
- }
- }
- int mn=INF; int mx=-INF;
- for (int i=0; i<h; i++) {
- for (int j=w-1; j>bds[i+1]; j--) {
- mn=min(mn,arr[i][j]);
- mx=max(mx,arr[i][j]);
- }
- }
- if (mx==-INF || mx-mn<=k) return true;
- return false;
- }
- void flip() {
- int h=sz(arr);
- int w=sz(arr[0]);
- adj.resize(h);
- for (int i=0; i<h; i++) {
- adj[i].resize(w);
- }
- for (int i=0; i<h; i++) {
- for (int j=0; j<w; j++) {
- adj[i][j]=arr[i][w-1-j];
- }
- }
- swap(adj,arr);
- }
- void rot() {
- int h=sz(arr);
- int w=sz(arr[0]);
- adj.resize(w);
- for (int i=0; i<w; i++) {
- adj[i].resize(h);
- }
- for (int i=0; i<h; i++) {
- for (int j=0; j<w; j++) {
- adj[j][i]=arr[h-i-1][j];
- }
- }
- swap(adj,arr);
- }
- int bsearch() {
- int lo=0; int hi=5e9;
- while (lo<=hi) {
- int mid=(lo+hi)/2;
- if (verif(mid)) {
- hi=mid-1;
- } else {
- lo=mid+1;
- }
- }
- return lo;
- }
- signed main() {
- ios::sync_with_stdio(false); cin.tie(nullptr);
- cin>>h>>w;
- arr=v2i(h,vi(w));
- for (int i=0; i<h; i++) {
- for (int j=0; j<w; j++) {
- cin>>arr[i][j]; smin=min(smin,arr[i][j]);
- }
- }
- int emin=INF;
- for (int i=0; i<4; i++) {
- emin=min(emin,bsearch());
- flip();
- emin=min(emin,bsearch());
- flip(); rot();
- }
- cout<<emin;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement