#include <bits/stdc++.h>
using namespace std;
#include "locmin.h"

#define endl '\n'
#define pb push_back
using ll = long long;
#define int ll
using pi = array<int, 2>;
using ti = array<int, 3>;

const int INF = 1e18 + 1;

std::pair<int32_t, int32_t> find_locmin_point(int32_t n, int32_t m) {
  vector<vector<int>> mat(n + 1, vector<int>(m + 1));
  auto query = [&](int i, int j) -> int {
    if (mat[i][j] == 0) {
      mat[i][j] = value(i, j);
    }
    return mat[i][j];
  };
  
  ti global{INF, 0, 0};
  int l1 = 1, r1 = n, l2 = 1, r2 = m;
  while (true) {
    if (r1 - l1 >= r2 - l2) { // fac linie
      int mid = (l1 + r1) / 2;
      
      pi minim{INF, 0};
      for (int i = l2; i <= r2; ++i) {
        minim = min(minim, {query(mid, i), i});
      }
      
      int idx = minim[1], up = INF, down = INF;
      if (mid > l1) {
        up = query(mid - 1, idx);
      }
      if (mid < r1) {
        down = query(mid + 1, idx);
      }
      
      if (minim[0] < global[0]) {
        if (up >= minim[0] && down >= minim[0]) {
          return {mid, idx};
        } else if (up < minim[0]) {
          r1 = mid - 1;
        } else {
          l1 = mid + 1;
        }
      } else {
        if (global[1] <= mid) {
          r1 = mid;
        } else {
          l1 = mid + 1;
        }
      }
      
      if (minim[0] < global[0]) global = {minim[0], mid, idx};
    } else {
      int mid = (l2 + r2) / 2;
      
      pi minim{INF, 0};
      for (int i = l1; i <= r1; ++i) {
        minim = min(minim, {query(i, mid), i});
      }
      
      int idx = minim[1], left = INF, right = INF;
      if (mid > l2) {
        left = query(idx, mid - 1);
      }
      if (mid < r2) {
        right = query(idx, mid + 1);
      }
      
      if (minim[0] < global[0]) {
        if (left >= minim[0] && right >= minim[0]) {
          return {idx, mid};
        } else if (left < minim[0]) {
          r2 = mid - 1;
        } else {
          l2 = mid + 1;
        }
      } else {
        if (global[2] <= mid) {
          r2 = mid;
        } else {
          l2 = mid + 1;
        }
      }
      
      if (minim[0] < global[0]) global = {minim[0], idx, mid};
    }
  }
}
