#include<iostream>
#include<random>
#include<climits>
#define MAXNN 510
#include "locmin.h"
using namespace std;
long long table[MAXNN][MAXNN];
int find_minimum(int row, int m)
{
    int l=1,r=m;
    while(r-l>1)
    {
        int mid=(l+r)>>1;
        long long curr;
        if(table[row][mid])curr=table[row][mid];
        else {curr=value(row,mid);table[row][mid]=curr;}

        long long left=LLONG_MAX,right=LLONG_MAX;
        if(mid>l)
        {
            if(table[row][mid-1])left=table[row][mid-1];
            else {left=value(row,mid-1);table[row][mid-1]=left;}
        }
        if(mid<r)
        {
            if(table[row][mid+1])right=table[row][mid+1];
            else {right=value(row,mid+1);table[row][mid+1]=right;}
        }
        if(left<=curr && left<=right)r=mid;
        else if(right<=left && right<=curr)l=mid;
        else
        {
            if(left!=LLONG_MAX)r=mid;
            else l=mid;
        }
    }
    if(table[row][l]<table[row][r])return l;
    return r;
}
pair <int, int> find_locmin_point(int n, int m)
{
    int l=1,r=n;
    while(l!=r)
    {
        int mid=(l+r)>>1;
        int ind=find_minimum(mid,m);
        long long val=table[mid][ind];
        long long up=LLONG_MAX,down=LLONG_MAX;
        if(mid>l)
        {
            if(table[mid-1][ind])up=table[mid-1][ind];
            else {up=value(mid-1,ind);table[mid-1][ind]=up;}
        }
        if(mid<r)
        {
            if(table[mid+1][ind])down=table[mid+1][ind];
            else {down=value(mid+1,ind);table[mid+1][ind]=down;}
        }
        if(val<up && val<down)return {mid,ind};
        else if(up<val)r=mid-1;
        else l=mid+1;
    }
    return {l,find_minimum(l,m)};
}