#include <bits/stdc++.h>
#include "locmin.h"

long long inf = 1e18;
using namespace std;

map<pair<int,int>,long long> mapa;
int n,m;

long long findV(pair<int,int> x)
{
    if(x.first < 1 || x.second < 1 || x.first > n || x.second > m) return inf;

    if(mapa.count(x)) return mapa[x];

    long long rez = value(x.first, x.second);
    mapa[x] = rez;
    return rez;
}

pair<int,int> solve(int a1, int a2, int b1, int b2)
{
    if(a1 == a2 && b1 == b2) return {a1, b1};

    int mida = a1 + a2 >> 1;
    int midb = b1 + b2 >> 1;

    long long mn = inf;
    int tl = -1, tr = -1;

    for(int i = b1; i <= b2; i++)
    {
        long long v = findV({mida, i});
        if(v < mn)
        {
            mn = v;
            tl = mida;
            tr = i;
        }
    }

    for(int i = a1; i <= a2; i++)
    {
        long long v = findV({i, midb});
        if(v < mn)
        {
            mn = v;
            tl = i;
            tr = midb;
        }
    }

    long long v = findV({tl, tr});
    long long gore = findV({tl-1, tr});
    long long dole = findV({tl+1, tr});
    long long levo = findV({tl, tr-1});
    long long desno = findV({tl, tr+1});

    if(v < levo && v < desno && v < gore && v < dole)
        return {tl, tr};

    if(v > gore) return solve(a1, mida-1, b1, b2);
    if(v > dole) return solve(mida+1, a2, b1, b2);
    if(v > levo) return solve(a1, a2, b1, midb-1);
    if(v > desno) return solve(a1, a2, midb+1, b2);

    return {tl, tr};
}

std::pair<int,int> find_locmin_point(int N, int M)
{
    n = N;
    m = M;
    mapa.clear();
    return solve(1, N, 1, M);
}
