Problem: cf2163_d2
Difficulty: easy
Categories: data structures, search, math
Time limit: 3000 ms, memory limit: 256 MB

This is the Hard version of the problem. The difference between the versions is that in this version, you can make at most $30$ queries. 

This problem is interactive.

There is a permutation$^{\text{∗}}$ $p$ of the integers from $0$ to $n-1$ hidden from you. Additionally, you are given $q$ ranges $[l_1, r_1], [l_2, r_2], \ldots, [l_q, r_q]$ where $1 \le l_i \le r_i \le n$.

You need to discover the maximum $\operatorname{MEX}$ among the values of $p$ in the $q$ ranges that are given to you in the input. Formally, you must discover the value of $\max _{i=1}^q {\operatorname{MEX}([p_{l_i}, p_{l_i+1}, \ldots, p_{r_i}])}$$^{\text{†}}$. To do this, you may make at most $30$ queries of the following form:

* Choose any two integers $1 \le l \le r \le n$ and you will receive the value $\operatorname{MEX}([p_{l}, p_{l+1}, \ldots, p_{r}])$.

$^{\text{∗}}$A permutation of the integers from $0$ to $n-1$ is a sequence of $n$ elements where every integer from $0$ to $n-1$ appears exactly once. For example, the sequence $[0, 3, 1, 2]$ is a permutation, but the sequence $[0, 0, 2, 1]$ is not.

$^{\text{†}}$The $\operatorname{MEX}$ of a sequence is defined as the smallest non-negative integer that does not appear in that sequence. For example, $\operatorname{MEX}([0, 0, 1, 3]) = 2$ and $\operatorname{MEX}([1, 2, 2]) = 0.$

Input

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). The description of the test cases follows.

The first line of each test case contains exactly two integers $n$ and $q$ ($4 \le n \le 10^4$, $1 \le q \le 3 \cdot 10^5$) — the size of the permutation and the number of ranges, respectively.

The $i$-th of the next $q$ lines contains two integers $l_i, r_i$ ($1 \le l_i \le r_i \le n$).

It is guaranteed that the sum of $n$ and $q$ do not exceed $10^4$ and $3 \cdot 10^5$ respectively over all test cases.

Additional Constraint: it is guaranteed that no range is repeated in the same test case.

Interaction

To ask a query, output a line in the following format (without the quotes):

* "? $l$ $r$" ($1 \le l \le r \le n$)

The jury will return a single integer, the value of $\operatorname{MEX}([p_{l}, p_{l+1}, \ldots, p_{r}])$.

When you have found the answer, output a single line in the following format:

* "! $x$" ($0 \le x \le n$).

After that, proceed to process the next test case or terminate the program if it was the last test case. Printing the answer does not count as a query.

The interactor is not adaptive, meaning that the values of the permutation are known before the participant asks the queries.

If your program makes more than $30$ queries, your program should immediately terminate to receive the verdict Wrong Answer. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.

After printing a query do not forget to output the end of line and flush the output. Otherwise, you may get the Idleness Limit Exceeded verdict. To do this, use:

* fflush(stdout) or cout.flush() in C++
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.

Example

Input

```
3
4 3
1 2
2 4
1 3

2

0

1

4

6 6
1 2
2 4
3 3
4 6
5 5
6 6

6

1

2

4 4
1 1
2 2
3 3
4 4
```

Output

```
? 1 3

? 4 4

? 1 1

? 1 4

! 2

? 1 6

? 3 3

? 2 4

! 2

! 1
```

Note

In the first example, the hidden permutation is $p = [0, 3, 1, 2]$ and the ranges are $[1, 2], [2, 4], [1, 3]$. The third range is optimal, as $\operatorname{MEX}([p_1, p_2, p_3]) = \operatorname{MEX}([0, 3, 1]) = 2$, which is maximum.

In our first query, we ask about $l = 1, r = 3$ and the judge gives us the value $\operatorname{MEX}([p_1, p_2, p_3]) = 2$. In the second query, we ask about $l = 4, r = 4$ and the judge gives us the value $\operatorname{MEX}([p_4]) = 0$. Likewise, $\operatorname{MEX}([p_1]) = 1$ and $\operatorname{MEX}([p_1, p_2, p_3, p_4]) = 4$.

Somehow, we figure out that the answer we are looking for is $2$.

In the second example, $p = [3, 5, 0, 1, 4, 2]$.

In the third example, $p = [0, 1, 2, 3]$.

Note that this is just an explanation of the way the interaction works and does not show any strategy to solve the problem.

Non-adaptive interactor (C++):
#include "testlib.h"
#include <algorithm>
#include <csignal>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

static int queries = 0;
static long long query_limit = -1;

void log_queries() {
    tout << "queries=" << queries << "\n";
    tout << "query_limit=" << query_limit << "\n";
}

void quit_with(TResult verdict, const string& msg) {
    log_queries();
    quitf(verdict, "%s", msg.c_str());
}

int main(int argc, char* argv[]) {
    registerInteraction(argc, argv);
    signal(SIGPIPE, SIG_IGN);
    atexit(log_queries);

    const int t = inf.readInt();
    cout << t << "\n" << flush;

    query_limit = 30;

    for (int tc = 0; tc < t; tc++) {
        const int n = inf.readInt();
        const int q = inf.readInt();
        vector<pair<int, int>> ranges(q);
        for (int i = 0; i < q; i++) {
            ranges[i].first = inf.readInt();
            ranges[i].second = inf.readInt();
        }
        vector<int> p(n + 1);
        for (int i = 1; i <= n; i++) {
            p[i] = inf.readInt();
            if (p[i] < 0 || p[i] >= n) {
                quit_with(_fail, "Invalid permutation value");
            }
        }

        const int words = (n + 63) / 64;
        vector<uint64_t> pref((n + 1) * words, 0);
        for (int i = 1; i <= n; i++) {
            uint64_t* dst = pref.data() + i * words;
            uint64_t* src = pref.data() + (i - 1) * words;
            memcpy(dst, src, size_t(words) * sizeof(uint64_t));
            const int v = p[i];
            dst[v >> 6] |= (uint64_t(1) << (v & 63));
        }

        auto mex_range = [&](int l, int r) -> int {
            const uint64_t* a = pref.data() + r * words;
            const uint64_t* b = pref.data() + (l - 1) * words;
            const int rem = n & 63;
            const uint64_t last_mask = (rem == 0) ? ~uint64_t(0) : ((uint64_t(1) << rem) - 1);

            for (int w = 0; w < words; w++) {
                uint64_t present = a[w] ^ b[w];
                uint64_t missing = ~present;
                if (w == words - 1) {
                    missing &= last_mask;
                }
                if (missing == 0) {
                    continue;
                }
                return w * 64 + __builtin_ctzll(missing);
            }
            return n;
        };

        int expected = 0;
        for (auto [l, r] : ranges) {
            if (l > r) {
                swap(l, r);
            }
            expected = max(expected, mex_range(l, r));
        }

        cout << n << " " << q << "\n";
        for (auto [l, r] : ranges) {
            cout << l << " " << r << "\n";
        }
        cout << flush;

        int used = 0;
        while (true) {
            string cmd;
            if (!(cin >> cmd)) {
                quit_with(_pe, "Unexpected EOF");
            }

            if (cmd == "?") {
                int l, r;
                if (!(cin >> l >> r)) {
                    quit_with(_pe, "Invalid query");
                }
                used++;
                queries++;
                if (used > query_limit) {
                    quit_with(_pe, "Too many queries");
                }
                if (!(1 <= l && l <= r && r <= n)) {
                    quit_with(_pe, "Query out of range");
                }
                cout << mex_range(l, r) << "\n" << flush;
                continue;
            }

            if (cmd == "!") {
                int ans;
                if (!(cin >> ans)) {
                    quit_with(_pe, "Missing answer");
                }
                if (ans != expected) {
                    quit_with(_wa, "Wrong answer");
                }
                break;
            }

            quit_with(_pe, "Unknown command: " + cmd);
        }
    }

    quit_with(_ok, "All tests correct");
}


Adaptive interactor (C++):

Test generator (C++):
#include "testlib.h"
#include <bits/stdc++.h>

using namespace std;

int main(int argc, char* argv[]) {
    registerGen(argc, argv, 1);

    
    
    
    string mode = opt<string>("mode", "non");
    long long seed_val = atoll(argv[1]);

    const int MAX_SUM_N = 10000;
    const int MAX_SUM_Q = 300000;

    
    if (seed_val == 1) {
        int tt = 2;
        cout << tt << endl;
        
        
        cout << "4 3" << endl;
        cout << "1 2\n2 4\n1 3" << endl;
        if (mode == "non") cout << "0 3 1 2" << endl;

        
        cout << "6 6" << endl;
        cout << "1 2\n2 4\n3 3\n4 6\n5 5\n6 6" << endl;
        if (mode == "non") cout << "3 5 0 1 4 2" << endl;
        
        return 0;
    }
    
    
    
    int t;
    
    
    if (rnd.next(3) == 0) {
        t = 1;
    } else {
        t = rnd.next(1, 10);
    }

    
    
    vector<int> ns(t, 4);
    long long rem_n = MAX_SUM_N - 4LL * t;
    
    vector<long long> n_parts = rnd.partition(t, rem_n);
    for(int i=0; i<t; ++i) ns[i] += (int)n_parts[i];

    vector<int> qs(t, 1);
    long long rem_q = MAX_SUM_Q - 1LL * t;
    
    vector<long long> q_parts = rnd.partition(t, rem_q);
    for(int i=0; i<t; ++i) qs[i] += (int)q_parts[i];

    cout << t << endl;

    for (int i = 0; i < t; ++i) {
        int n = ns[i];
        int q = qs[i];
        
        int max_ranges = (long long)n * (n + 1) / 2;
        if (q > max_ranges) q = max_ranges;
        cout << n << " " << q << endl;

        
        set<pair<int, int>> ranges_set;
        vector<pair<int, int>> ranges_vec;

        auto add_range = [&](int u, int v) {
            if (u > v) swap(u, v);
            if (ranges_set.count({u, v})) return;
            ranges_set.insert({u, v});
            ranges_vec.push_back({u, v});
        };

        
        add_range(1, n);
        add_range(1, 1);
        add_range(n, n);
        
        
        
        
        while ((int)ranges_set.size() < q) {
            int u = rnd.next(1, n);
            int v = rnd.next(1, n);
            add_range(u, v);
        }

        
        shuffle(ranges_vec.begin(), ranges_vec.end());

        for (const auto& p : ranges_vec) {
            cout << p.first << " " << p.second << "\n";
        }

        if (mode == "non") {
            
            vector<int> p(n);
            iota(p.begin(), p.end(), 0);

            
            int type = rnd.next(10);
            if (type < 6) {
                
                shuffle(p.begin(), p.end());
            } else if (type < 8) {
                
                reverse(p.begin(), p.end());
                int swaps = rnd.next(1, max(1, n / 20));
                for (int k = 0; k < swaps; ++k) {
                    int a = rnd.next(n);
                    int b = rnd.next(n);
                    swap(p[a], p[b]);
                }
            } else {
                
                int swaps = rnd.next(n / 10, n / 2);
                for (int k = 0; k < swaps; ++k) {
                    int a = rnd.next(n);
                    int b = rnd.next(n);
                    swap(p[a], p[b]);
                }
            }

            for (int k = 0; k < n; ++k) {
                cout << p[k] << (k == n - 1 ? "" : " ");
            }
            cout << endl;
        } else {
            
            
            
            
        }
    }

    return 0;
}