#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)
{
    long long mn=LLONG_MAX;
    long long idx=-1;
    for(long long i=1;i<=m;i++)
    {
        if(table[row][i]==0) table[row][i]=value(row,i);
        if(table[row][i]<mn) {mn=table[row][i];idx=i;}
    }
    return idx;
}
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)};
}
