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

#define int long long

int a[505][505], n, m;

int ask(int i, int j) {
    if (a[i][j]) {
        return a[i][j];
    }
    if (!(1 <= i and i <= n and 1 <= j and j <= m)) {
        return 2e18;
    }
    return a[i][j] = value(i, j);
}

pair<int, int> f(int u, int d, int l, int r) {
    if (u > d or l > r) {
        return {-1, -1};
    }
    if (u == d and l == r) {
        return {u, l};
    }
    int n = d - u, m = r - l;
    if (n > m) {
        vector<int> v;
        int x = (u + d) / 2;
        for (int i = l; i <= r; i++) {
            v.push_back(a[x][i] = value(x, i));
        }
        int mn = min_element(v.begin(), v.end()) - v.begin() + l;
        if (ask(x - 1, mn) < a[x][mn]) {
            return f(u, x - 1, l, r);
        } else if (ask(x + 1, mn) < a[x][mn]) {
            return f(x + 1, d, l, r);
        } else {
            return {x, mn};
        }
    } else {
        vector<int> v;
        int x = (l + r) / 2;
        for (int i = u; i <= d; i++) {
            v.push_back(a[i][x] = value(i, x));
        }
        int mn = min_element(v.begin(), v.end()) - v.begin() + u;
        if (ask(mn, x - 1) < a[mn][x]) {
            return f(u, d, l, x - 1);
        } else if (ask(mn, x + 1) < a[mn][x]) {
            return f(u, d, x + 1, r);
        } else {
            return {mn, x};
        }
    }
}

#undef int

pair<int, int> find_locmin_point(int N, int M) {
    n = N, m = M;
    return f(1, n, 1, m);
}
