#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
vector<vector<long long>> grid;
vector<pair<long long,long long>> moves = {{0,-1},{0,1},{-1,0},{1,0}};
long long h,w;
multiset<long long> ogvals;
long long bfs(long long mid){
multiset<long long> vals = ogvals;
queue<pair<pair<long long,long long>,long long>> nodes;
long long difference = 0;
long long first = grid[0][0];
nodes.push({{0,0},first});
vals.erase(first);
vector<vector<bool>> vis;
vis.resize(h,vector<bool>(w,false));
vis[0][0] = true;
while (!nodes.empty()){
long long cr = nodes.front().first.first;
long long cc = nodes.front().first.second;
long long cval = nodes.front().second;
nodes.pop();
for(auto move : moves){
long long nr = cr + move.first;
long long nc = cc + move.second;
if (nr >= 0 && nr < h && nc >= 0 && nc < w && vis[nr][nc] != true){
long long newval = grid[nr][nc];
nodes.push({{nr,nc},newval});
vis[nr][nc] = true;
long long temp = difference;
difference = max(difference,newval - cval); // tracks max difference in one kingdom
vals.erase(vals.find(newval));
if (difference > mid){
vals.insert(newval);
difference = temp;
auto it = prev(vals.end());
auto it2 = vals.begin();
long long maxdiff = *it - *it2;
return max(difference,maxdiff);
}
else if (difference == mid){
auto it = prev(vals.end());
auto it2 = vals.begin();
long long maxdiff = *it - *it2;
return max(difference,maxdiff);
}
}
}
}
return difference;
}
bool check(long long mid){
long long r = bfs(mid);
return r <= mid;
}
void bsearch(){
long long lb = 0;
long long ub = 1e9;
long long mid = -1;
long long res = -1;
while (lb <= ub){
mid = (lb + ub) / 2;
if (check(mid)){
res = mid;
ub = mid - 1;
}
else{
lb = mid + 1;
}
}
cout << res;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> h >> w;
grid.resize(h,vector<long long>(w));
for(int i = 0;i<h;i++){
for(int j = 0;j<w;j++){
long long alt;cin >> alt;
grid[i][j] = alt;
ogvals.insert(alt);
}
}
bsearch();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |