#include "locmin.h"
#include <map>
using namespace std;

map<pair<int,int>, long long> mp;

long long val(int r,int c){
    if(mp.count({r,c})) return mp[{r,c}];
    return mp[{r,c}] = value(r,c);
}

pair<int,int> solve_lignes(int N,int M,int haut,int bas){
    int mid = (haut + bas) / 2;

    int c = 1;
    long long best = val(mid,1);
    for(int j=2;j<=M;j++){
        long long v = val(mid,j);
        if(v < best){
            best = v;
            c = j;
        }
    }

    long long up = (mid>1 ? val(mid-1,c) : 1e18);
    long long down = (mid<N ? val(mid+1,c) : 1e18);

    if(best < up && best < down) return {mid,c};

    if(up < best) return solve_lignes(N,M,haut,mid-1);
    return solve_lignes(N,M,mid+1,bas);
}

pair<int,int> solve_cols(int N,int M,int gauche,int droite){
    int mid = (gauche + droite) / 2;

    int r = 1;
    long long best = val(1,mid);
    for(int i=2;i<=N;i++){
        long long v = val(i,mid);
        if(v < best){
            best = v;
            r = i;
        }
    }

    long long left = (mid>1 ? val(r,mid-1) : 1e18);
    long long right = (mid<M ? val(r,mid+1) : 1e18);

    if(best < left && best < right) return {r,mid};

    if(left < best) return solve_cols(N,M,gauche,mid-1);
    return solve_cols(N,M,mid+1,droite);
}

pair<int,int> find_locmin_point(int N,int M){
    if(N <= M) return solve_lignes(N,M,1,N);
    return solve_cols(N,M,1,M);
}