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

map<pair<int,int>, long long> mp;
const long long INF = (long long)4e18;

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> solveL(int n,int m,int h,int b){
    int mid=(h+b)/2;

    int bc=1;
    long long bv=val(mid,1);

    for(int j=2;j<=m;j++){
        long long v=val(mid,j);
        if(v<bv){bv=v;bc=j;}
    }

    long long vg,vd;
    if(mid>1) vg=val(mid-1,bc);
    else vg=INF;
    if(mid<n) vd=val(mid+1,bc);
    else vd=INF;

    if(bv<vg && bv<vd) return {mid,bc};
    if(vg<bv) return solveL(n,m,h,mid-1);
    return solveL(n,m,mid+1,b);
}

pair<int,int> solveC(int n,int m,int g,int d){
    int mid=(g+d)/2;

    int br=1;
    long long bv=val(1,mid);

    for(int i=2;i<=n;i++){
        long long v=val(i,mid);
        if(v<bv){bv=v;br=i;}
    }

    long long vg,vd;
    if(mid>1) vg=val(br,mid-1);
    else vg=INF;
    if(mid<m) vd=val(br,mid+1);
    else vd=INF;

    if(bv<vg && bv<vd) return {br,mid};
    if(vg<bv) return solveC(n,m,g,mid-1);
    return solveC(n,m,mid+1,d);
}

pair<int,int> find_locmin_point(int N,int M){
    if(N < M) return solveL(N,M,1,N);
    return solveC(N,M,1,M);
}