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

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

long long get(long long x, long long y) {
    if (x < 0 || y < 0 || x >= N || y >= M) {
        return 1e18;
    }
    if (mp.find({x, y}) != mp.end()) {
        return mp[{x, y}];
    }
    // cout << "! " << x << " " << y + << endl;
    return mp[{x, y}] = value(x + 1, y + 1);
}
mt19937 rnd(10);

pair <int, int> find_locmin_point(int N2, int M2) {
    N = N2;
    M = M2;
    long long x = rnd() % N, y = rnd() % M;
    long long cnt = 0;
    while (true) {
        cnt++;
        if (cnt > N * M) {
            throw(0);
        }
        if (min({get(x, y), get(x, y - 1), get(x - 1, y), get(x, y + 1), get(x + 1, y)}) == get(x, y)) {
            break;
        }
        if (min({get(x, y), get(x, y - 1), get(x - 1, y), get(x, y + 1), get(x + 1, y)}) == get(x - 1, y)) {
            x--;
            continue;
        }
        if (min({get(x, y), get(x, y - 1), get(x - 1, y), get(x, y + 1), get(x + 1, y)}) == get(x + 1, y)) {
            x++;
            continue;
        }
        if (min({get(x, y), get(x, y - 1), get(x - 1, y), get(x, y + 1), get(x + 1, y)}) == get(x, y - 1)) {
            y--;
            continue;
        }
        y++;
    }
    return {x + 1, y + 1};
}
