File size: 10,982 Bytes
1fd0050
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#include <bits/stdc++.h>
using namespace std;

int n;
long long k;
vector<long long> memo;
int query_count = 0;

long long do_query(int r, int c) {
    int key = r * 2001 + c;
    if (memo[key] != -1) return memo[key];
    cout << "QUERY " << r << " " << c << "\n";
    cout.flush();
    long long v;
    cin >> v;
    memo[key] = v;
    query_count++;
    return v;
}

void done(long long ans) {
    cout << "DONE " << ans << "\n";
    cout.flush();
    exit(0);
}

// Staircase walk: count elements <= x, track boundary per row
// posOut[i] = max column j such that a[i][j] <= x (0 if none)
// Walk top-to-bottom, right-to-left: O(n) new queries (with caching, even less)
long long count_leq(long long x, vector<int>& pos) {
    pos.assign(n + 1, 0);
    long long cnt = 0;
    int j = n;
    for (int i = 1; i <= n; i++) {
        while (j >= 1 && do_query(i, j) > x) j--;
        pos[i] = j;
        cnt += j;
        if (j == 0) {
            for (int ii = i + 1; ii <= n; ii++) pos[ii] = 0;
            break;
        }
    }
    return cnt;
}

long long count_lt(long long x, vector<int>& pos) {
    pos.assign(n + 1, 0);
    long long cnt = 0;
    int j = n;
    for (int i = 1; i <= n; i++) {
        while (j >= 1 && do_query(i, j) >= x) j--;
        pos[i] = j;
        cnt += j;
        if (j == 0) {
            for (int ii = i + 1; ii <= n; ii++) pos[ii] = 0;
            break;
        }
    }
    return cnt;
}

// Bounded staircase walk: only check within posLow[i]+1..posHigh[i]
// More query-efficient when bounds are tight
long long count_leq_bounded(long long x, vector<int>& pos, const vector<int>& lo, const vector<int>& hi) {
    pos.assign(n + 1, 0);
    long long cnt = 0;
    // For row i, we know answer is in [lo[i]+1, hi[i]]
    // Walk top to bottom. j starts from hi[1] and decreases.
    int j = n; // will be clamped
    for (int i = 1; i <= n; i++) {
        j = min(j, hi[i]);
        if (j < 1) {
            pos[i] = 0;
            for (int ii = i + 1; ii <= n; ii++) pos[ii] = 0;
            break;
        }
        while (j >= 1 && do_query(i, j) > x) j--;
        pos[i] = j;
        cnt += max(0, j);
        if (j == 0) {
            for (int ii = i + 1; ii <= n; ii++) pos[ii] = 0;
            break;
        }
    }
    return cnt;
}

void solve() {
    long long N2 = (long long)n * n;

    if (n == 1) { done(do_query(1, 1)); return; }
    if (k == 1) { done(do_query(1, 1)); return; }
    if (k == N2) { done(do_query(n, n)); return; }

    // For small k or k close to N2, use heap directly
    long long heap_k = min(k, N2 - k + 1);
    if (heap_k + n <= 24000) {
        if (k <= N2 - k + 1) {
            // k-th smallest via min-heap on rows
            priority_queue<tuple<long long, int, int>, vector<tuple<long long, int, int>>, greater<>> pq;
            for (int i = 1; i <= n; i++)
                pq.emplace(do_query(i, 1), i, 1);
            long long result = -1;
            for (long long t = 0; t < k; t++) {
                auto [v, r, c] = pq.top(); pq.pop();
                result = v;
                if (c + 1 <= n) pq.emplace(do_query(r, c + 1), r, c + 1);
            }
            done(result);
        } else {
            long long kk = N2 - k + 1;
            priority_queue<tuple<long long, int, int>> pq;
            for (int i = 1; i <= n; i++)
                pq.emplace(do_query(i, n), i, n);
            long long result = -1;
            for (long long t = 0; t < kk; t++) {
                auto [v, r, c] = pq.top(); pq.pop();
                result = v;
                if (c - 1 >= 1) pq.emplace(do_query(r, c - 1), r, c - 1);
            }
            done(result);
        }
    }

    // Value-based narrowing approach
    mt19937_64 rng(12345);

    // Initialize: posHigh from count_leq(a[n][n]), posLow all 0
    vector<int> posHigh(n + 1, n), posLow(n + 1, 0);
    long long cntHigh = N2, cntLow = 0;
    long long highTh, lowTh;

    // Get initial bounds - use anti-diagonal estimate
    // Row ceil(k/n): a[ceil(k/n)][n] is an upper bound
    int rBound = (int)min((long long)n, (k + n - 1) / n);
    highTh = do_query(rBound, n);
    cntHigh = count_leq(highTh, posHigh);
    if (cntHigh < k) {
        highTh = do_query(n, n);
        cntHigh = count_leq(highTh, posHigh);
    }

    // Lower bound: a[floor(k/n)+1][1] or just 0
    // Actually, row floor(k/n): a[floor(k/n)][1] has at most floor(k/n)*n elements <= it from first floor(k/n) rows
    // But it's more complex. Just use cntLow = 0 initially.
    lowTh = do_query(1, 1) - 1; // everything is >= a[1][1]
    // posLow stays all 0

    const int SAMPLES = 15;

    for (int iter = 0; iter < 200; iter++) {
        if (cntHigh < k) {
            highTh = do_query(n, n);
            cntHigh = count_leq(highTh, posHigh);
            if (cntHigh < k) break; // shouldn't happen
        }

        long long candTotal = cntHigh - cntLow;
        if (candTotal <= 0) { done(highTh); }

        long long needSmall = k - cntLow;
        long long needLarge = cntHigh - k + 1;

        // Count non-empty rows and build prefix sums for sampling
        vector<long long> pref(n + 1, 0);
        int nonempty = 0;
        for (int i = 1; i <= n; i++) {
            int len = posHigh[i] - posLow[i];
            if (len > 0) nonempty++;
            pref[i] = pref[i - 1] + max(0, len);
        }
        candTotal = pref[n];
        if (candTotal <= 0) { done(highTh); }

        // Check if we can enumerate directly
        long long budget = 49500 - query_count;
        long long enumCost = min(needSmall, needLarge) + nonempty + 10;
        if (enumCost <= budget) {
            // Enumerate via heap
            if (needSmall <= needLarge) {
                priority_queue<tuple<long long, int, int>, vector<tuple<long long, int, int>>, greater<>> pq;
                for (int i = 1; i <= n; i++) {
                    int L = posLow[i] + 1;
                    int R = posHigh[i];
                    if (L >= 1 && L <= n && L <= R) {
                        pq.emplace(do_query(i, L), i, L);
                    }
                }
                long long result = 0;
                for (long long t = 0; t < needSmall; t++) {
                    auto [v, r, c] = pq.top(); pq.pop();
                    result = v;
                    if (c + 1 <= posHigh[r]) pq.emplace(do_query(r, c + 1), r, c + 1);
                }
                done(result);
            } else {
                priority_queue<tuple<long long, int, int>> pq;
                for (int i = 1; i <= n; i++) {
                    int L = posLow[i] + 1;
                    int R = posHigh[i];
                    if (R >= 1 && R <= n && L <= R) {
                        pq.emplace(do_query(i, R), i, R);
                    }
                }
                long long result = 0;
                for (long long t = 0; t < needLarge; t++) {
                    auto [v, r, c] = pq.top(); pq.pop();
                    result = v;
                    int L = posLow[r] + 1;
                    if (c - 1 >= L) pq.emplace(do_query(r, c - 1), r, c - 1);
                }
                done(result);
            }
        }

        // Budget check for another iteration
        if (budget < 2 * n + SAMPLES + 200) {
            // Try to enumerate anyway
            if (nonempty + min(needSmall, needLarge) + 10 <= budget) {
                // same enumeration as above
                if (needSmall <= needLarge) {
                    priority_queue<tuple<long long, int, int>, vector<tuple<long long, int, int>>, greater<>> pq;
                    for (int i = 1; i <= n; i++) {
                        int L = posLow[i] + 1, R = posHigh[i];
                        if (L >= 1 && L <= n && L <= R) pq.emplace(do_query(i, L), i, L);
                    }
                    long long result = 0;
                    for (long long t = 0; t < needSmall; t++) {
                        auto [v, r, c] = pq.top(); pq.pop();
                        result = v;
                        if (c + 1 <= posHigh[r]) pq.emplace(do_query(r, c + 1), r, c + 1);
                    }
                    done(result);
                } else {
                    priority_queue<tuple<long long, int, int>> pq;
                    for (int i = 1; i <= n; i++) {
                        int L = posLow[i] + 1, R = posHigh[i];
                        if (R >= 1 && R <= n && L <= R) pq.emplace(do_query(i, R), i, R);
                    }
                    long long result = 0;
                    for (long long t = 0; t < needLarge; t++) {
                        auto [v, r, c] = pq.top(); pq.pop();
                        result = v;
                        if (c - 1 >= posLow[r] + 1) pq.emplace(do_query(r, c - 1), r, c - 1);
                    }
                    done(result);
                }
            }
            done(highTh); // fallback
        }

        // Sample pivot values from candidate segments
        vector<long long> samp;
        samp.reserve(SAMPLES);
        for (int s = 0; s < SAMPLES; s++) {
            long long pick = 1 + rng() % candTotal;
            int row = (int)(lower_bound(pref.begin() + 1, pref.end(), pick) - pref.begin());
            if (row < 1 || row > n) continue;
            int len = posHigh[row] - posLow[row];
            if (len <= 0) { continue; }
            int col = posLow[row] + 1 + rng() % len;
            col = max(1, min(n, col));
            samp.push_back(do_query(row, col));
        }
        if (samp.empty()) { done(highTh); }

        sort(samp.begin(), samp.end());

        // Pick pivot at the quantile matching needSmall/candTotal
        double q = (double)needSmall / (double)candTotal;
        int idx = (int)(q * (double)(samp.size() - 1));
        idx = max(0, min((int)samp.size() - 1, idx));
        long long pivot = samp[idx];

        // Count elements <= pivot
        vector<int> posPivot;
        long long cntPivot = count_leq(pivot, posPivot);

        if (cntPivot >= k) {
            // Tighten high
            if (pivot == highTh && cntPivot == cntHigh) {
                // Pivot equals current high and same count - duplicates
                vector<int> posLess;
                long long cntLess = count_lt(pivot, posLess);
                if (cntLess < k) {
                    done(pivot); // k-th element equals pivot
                }
                // Narrow to strictly less than pivot
                highTh = pivot - 1;
                posHigh = posLess;
                cntHigh = cntLess;
            } else {
                highTh = pivot;
                posHigh = posPivot;
                cntHigh = cntPivot;
            }
        } else {
            // Tighten low
            lowTh = pivot;
            posLow = posPivot;
            cntLow = cntPivot;
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n >> k;
    memo.assign(2002 * 2002, -1);
    solve();
    return 0;
}