This is an interactive problem.

While procrastinating at work, Dilhan the elf stumbled upon two arrays $a$ and $b$. Initially, both of them consist of a single integer $2^k$ (i.e., $a=b=[2^k]$), where $k$ is a non-negative integer.

Dilhan then applied the following two types of operations an arbitrary number of times (possibly zero), in any order:

1. Flatten — Choose either $a$ or $b$, and select any element $x$ that is maximal within that array ($x$ does not need to be maximal in the other array). Then, replace $x$ with two copies of $\frac x2$ in the same position. This operation can only be applied if $x$ is even.
2. Concatenate — Set both $a$ and $b$ to be $a+b$, where $+$ denotes array concatenation.

After performing these operations, Dilhan discards $b$, hides $a$ from you, and challenges you to a game.

Let $n$ be the length of the hidden array $a$. You may make the following query:

* Choose an interval $[l, r]$ ($1\le l\le r\le n$), and Dilhan will tell you the sum $a_l+a_{l+1}+\cdots+a_r$.

Determine the value of the maximum element of $a$ by making at most $300$ queries.

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 a single integer $n$ ($1 \le n \le 10^5$) — the length of $a$.

It is guaranteed that $1\le a_i\le 2^{30}$, and the array $a$ can be generated by the process described in the statements.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.

Interaction

For each test case, you are first given an integer $n$ — the length of the hidden array $a$. You may then make up to $300$ queries.

To make a query, print a line in the following format:

* $\texttt{?}\;l\;r$ ($1\le l\le r\le n$) — the indices chosen for the query.

After you print a query, the interactor will respond with a single integer — the sum $a_l+a_{l+1}+\ldots+a_r$.

To report that you have determined the value of the maximum element of $a$, print your answer in the following format:

* $\texttt{!}\; m$ ($1\le m\le 2^{30}$) — the value of the maximum element.

Printing the answer does not count as one of the $300$ queries.

After printing the answer, proceed to the next test case. If the current test case is the last one, terminate the program.

After printing each query do not forget to output the end of line and flush$^{\text{∗}}$ the output. Otherwise, you will get Idleness limit exceeded verdict.

If, at any interaction step, you read $-1$ instead of valid data, your solution must exit immediately. This means that your solution will receive Wrong answer because of an invalid query or any other mistake. Failing to exit can result in an arbitrary verdict because your solution will continue to read from a closed stream.

The interactor in this problem is not adaptive. In other words, the array $a$ is fixed before any queries and will not change during the interaction.

$^{\text{∗}}$To flush, use:

* fflush(stdout) or cout.flush() in C++;
* sys.stdout.flush() in Python;
* see the documentation for other languages.

Example

Input

```
4
11

9

4

12

1

1

8

4

4

4

4

8
```

Output

```
? 3 8

? 1 4

? 5 11

! 2

? 1 1

! 1

? 1 1

? 2 2

? 3 3

? 4 4

! 4

! 1073741824
```

Note

In the first test case, Dilhan's hidden array $a$ is $[1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2]$. It can be generated by the following process:

|  |  |  |  |
| --- | --- | --- | --- |
| # | Type | $a$ after operation | $b$ after operation |
| 0 |  | $[4]$ | $[4]$ |
| 1 | Flatten $a$ | $[\underline 4] \to {[2, 2]}$ | $[4]$ |
| 2 | Flatten $b$ | $[2, 2]$ | $[\underline 4] \to {[2, 2]}$ |
| 3 | Flatten $a$ | $[2, \underline 2] \to {[2, 1, 1]}$ | $[2, 2]$ |
| 4 | Concatenate | $[2, 1, 1, 2, 2]$ | $[2, 1, 1, 2, 2]$ |
| 5 | Flatten $a$ | $[\underline 2, 1, 1, 2, 2]\to {[1, 1, 1, 1, 2, 2]}$ | $[2, 1, 1, 2, 2]$ |
| 6 | Concatenate | $[1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2]$ | $[1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 2]$ |

* For the query $\mathtt{?\;3\;8}$, the jury responded with $1+1+2+2+2+1=9$;
* For the query $\mathtt{?\;1\;4}$, the jury responded with $1+1+1+1=4$;
* For the query $\mathtt{?\;5\;11}$, the jury responded with $2+2+2+1+1+2+2=12$.

And the value of the maximum element of $a$ is $2$.

In the second test case, the array $a$ has only one element. By the query, the value of the only element is $1$, and it must also be the maximum value.

In the third test case, Dilhan's hidden array $a$ is $[4, 4, 4, 4, 4, 4, 4, 4]$. It can be generated by the following process:

|  |  |  |  |
| --- | --- | --- | --- |
| # | Type | $a$ after operation | $b$ after operation |
| 0 |  | $[4]$ | $[4]$ |
| 1 | Concatenate | $[4, 4]$ | $[4, 4]$ |
| 2 | Concatenate | $[4, 4, 4, 4]$ | $[4, 4, 4, 4]$ |
| 3 | Concatenate | $[4, 4, 4, 4, 4, 4, 4, 4]$ | $[4, 4, 4, 4, 4, 4, 4, 4]$ |

And the value of the maximum element of $a$ is $4$.

In the fourth test case, Dilhan's hidden array $a$ is $[2^{29}, 2^{29}, 2^{30}, 2^{29}, 2^{28}, 2^{28}, 2^{29}, 2^{29}]$.

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long queries = 0;
static long long query_limit = 0;
static const long long HARD_CAP = 200000;

static void log_metrics() {
    try {
        tout << "queries=" << queries << endl;
        tout << "query_limit=" << query_limit << endl;
    } catch (...) {

    }
}

template <typename... Args>
void finish(TResult verdict, const char* fmt, Args... args) {
    log_metrics();
    quitf(verdict, fmt, args...);
}

int read_action(int& l, int& r, long long& ans) {
    string token;

    if (!(cin >> token)) return -1;

    if (token == "!") {
        if (!(cin >> ans)) return -1;
        return 1;
    }

    if (token == "?") {
        if (!(cin >> l >> r)) return -1;
        return 0;
    }

    try {
        size_t idx;
        l = stoi(token, &idx);
        if (idx != token.size()) return -1;
    } catch (...) {
        return -1;
    }

    if (!(cin >> r)) return -1;
    return 0;
}

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

    registerInteraction(argc, argv);
    atexit(log_metrics);

    int t = inf.readInt();

    query_limit = 300LL * t;
    log_metrics();

    cout << t << endl;

    while (t--) {
        int n = inf.readInt();

        vector<long long> a(n);
        long long true_max = -1;

        for (int i = 0; i < n; i++) {
            a[i] = inf.readLong();
            if (true_max == -1 || a[i] > true_max) {
                true_max = a[i];
            }
        }

        vector<long long> p(n + 1, 0);
        for (int i = 0; i < n; i++) {
            p[i+1] = p[i] + a[i];
        }

        cout << n << endl;

        bool solved = false;
        while (true) {

            if (queries > HARD_CAP) {
                finish(_pe, "Hard query limit exceeded (%lld)", HARD_CAP);
            }

            int l = -1, r = -1;
            long long user_ans = -1;
            int type = read_action(l, r, user_ans);

            if (type == -1) {
                finish(_wa, "Unexpected EOF or malformed input");
            }

            if (type == 1) {

                if (user_ans == true_max) {
                    solved = true;
                    break;
                } else {
                    finish(_wa, "Incorrect answer: expected %lld, got %lld", true_max, user_ans);
                }
            } else {

                queries++;

                if (queries % 10 == 0) log_metrics();

                if (l < 1 || l > r || r > n) {
                    finish(_wa, "Invalid query range: [%d, %d] (n=%d)", l, r, n);
                }

                long long range_sum = p[r] - p[l-1];
                cout << range_sum << endl;
            }
        }

        if (!solved) {
            finish(_wa, "Loop terminated incorrectly");
        }
    }

    finish(_ok, "All cases passed");
    return 0;
}

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

string mode;

struct ArrayState {
    list<long long> L;

    map<long long, vector<list<long long>::iterator>> vals;

    void add(long long val, list<long long>::iterator it) {
        vals[val].push_back(it);
    }

    void copy_from(const ArrayState& other) {
        L.clear();
        vals.clear();
        for (auto x : other.L) {
            L.push_back(x);
            vals[x].push_back(prev(L.end()));
        }
    }

    void append(const ArrayState& other) {
        for (auto x : other.L) {
            L.push_back(x);
            vals[x].push_back(prev(L.end()));
        }
    }

    bool can_flatten() {
        if (vals.empty()) return false;
        long long m = vals.rbegin()->first;
        return (m % 2 == 0);
    }

    void flatten() {
        if (vals.empty()) return;
        long long m = vals.rbegin()->first;
        auto& vec = vals.rbegin()->second;

        if (vec.empty()) {
            vals.erase(m);
            return;
        }

        int idx = rnd.next(vec.size());
        auto it = vec[idx];

        vec[idx] = vec.back();
        vec.pop_back();
        if (vec.empty()) vals.erase(m);

        long long half = m / 2;

        *it = half;
        auto new_it = L.insert(next(it), half);

        vals[half].push_back(it);
        vals[half].push_back(new_it);
    }

    int size() const {
        return (int)L.size();
    }
};

static vector<long long> generate_flatten_only(int n, int k) {
    ArrayState A;
    long long start = 1LL << k;
    A.L.push_back(start);
    A.add(start, A.L.begin());

    while (A.size() < n) {
        if (!A.can_flatten()) break;
        A.flatten();
    }

    vector<long long> out;
    out.reserve(A.size());
    for (auto x : A.L) out.push_back(x);
    return out;
}

static void print_case(const vector<long long>& a) {
    cout << a.size() << "\n";
    for (int i = 0; i < (int)a.size(); i++) {
        if (i) cout << " ";
        cout << a[i];
    }
    cout << "\n";
}

int main(int argc, char* argv[]) {
    registerGen(argc, argv, 1);
    mode = opt<string>("mode", "non");

    long long seed_val = -1;
    try {
        seed_val = stoll(string(argv[1]));
    } catch (...) {
        seed_val = -1;
    }

    if (seed_val == 40) {
        const int t = 2;
        cout << t << "\n";

        print_case(generate_flatten_only(50000, 16));
        print_case(generate_flatten_only(50000, 30));
        return 0;
    }

    cout << 1 << "\n";

    int target_n = rnd.next(1000, 100000);

    if (rnd.next(10) == 0) target_n = rnd.next(1, 100);

    long long k;
    int type = rnd.next(100);
    if (type < 15) k = rnd.next(0, 5);
    else if (type < 30) k = rnd.next(25, 30);
    else k = rnd.next(0, 30);

    ArrayState A, B;

    A.L.push_back(1LL << k);
    A.add(1LL << k, A.L.begin());

    B.L.push_back(1LL << k);
    B.add(1LL << k, B.L.begin());

    const int MAX_N = 100000;
    int ops = 0;

    while (ops < 300000 && A.size() < target_n) {
        ops++;

        vector<int> moves;

        if (A.size() < MAX_N && A.can_flatten()) moves.push_back(0);
        if (B.size() < MAX_N && B.can_flatten()) moves.push_back(1);

        if ((long long)A.size() + B.size() <= MAX_N) {
            moves.push_back(2);
        }

        if (moves.empty()) break;

        int m = moves[rnd.next(moves.size())];

        if (m == 0) {
            A.flatten();
        } else if (m == 1) {
            B.flatten();
        } else {

            A.append(B);
            B.copy_from(A);
        }
    }

    cout << A.size() << endl;
    bool first = true;
    for (auto x : A.L) {
        if (!first) cout << " ";
        cout << x;
        first = false;
    }
    cout << endl;

    return 0;
}


![](https://espresso.codeforces.com/1b3f8506501b8393400b3a441a3b82b3bab2bb30.png)

This is an interactive problem.

We picked an array of whole numbers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) and concealed exactly one zero in it! Your goal is to find the location of this zero, that is, to find $i$ such that $a_i = 0$.

You are allowed to make several queries to guess the answer. For each query, you can think up three distinct indices $i, j, k$, and we will tell you the value of $\max(a_i, a_j, a_k) - \min(a_i, a_j, a_k)$. In other words, we will tell you the difference between the maximum and the minimum number among $a_i$, $a_j$ and $a_k$.

You are allowed to make no more than $2 \cdot n - 2$ queries, and after that you have two tries to guess where the zero is. That is, you have to tell us two numbers $i$ and $j$ and you win if $a_i = 0$ or $a_j = 0$.

Can you guess where we hid the zero?

Note that the array in each test case is fixed beforehand and will not change during the game. In other words, the interactor is not adaptive.

Input

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

The first and only line of each test case contains an integer $n$ ($4 \le n \le 1000$) — the length of the array that we picked.

It is guaranteed that the sum of $n$ over all test cases does not exceed $3000$.

Interaction

For each test case, the interaction starts with reading $n$.

To make a query, print "? $i$ $j$ $k$" (without quotes, $1 \le i, j, k \le n$, indices must be distinct). Then you should read our response from standard input, that is, $\max(a_i, a_j, a_k) - \min(a_i, a_j, a_k)$.

If the response is $-1$, it means your program has made an invalid query or has run out of tries. Your program must terminate immediately after reading $-1$, and you will get a verdict Wrong answer. Otherwise you may get any verdict, because the program will continue reading from the closed stream. Note that if the query is correct, the answer will never be $-1$ because $\max(a_i, a_j, a_k) - \min(a_i, a_j, a_k) \geq 0$.

To give the final answer, print "! $i$ $j$" (without the quotes). Printing the same number twice (that is, $i = j$) is allowed. Note that giving this answer is not counted towards the limit of $2 \cdot n - 2$ queries. After that, your program must continue to solve the remaining test cases, or exit if all test cases have been solved.

After printing a query, don't forget to output line feed and flush the output buffer. Otherwise you will get the verdict Idleness limit exceeded. To flush the buffer, use:

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

Example

Input

```
1

4

2

3

3

2
```

Output

```
? 1 2 3

? 2 3 4

? 3 4 1

? 4 1 2

! 2 3
```

Note

Array from sample: $[1, 2, 0, 3]$.

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long queries = 0;
static long long query_limit = 0;
static const long long HARD_CAP = 200000;

static ofstream log_fs;

static void log_metrics() {
    if (log_fs.is_open()) {
        log_fs << "queries=" << queries << endl;
        log_fs << "query_limit=" << query_limit << endl;
        log_fs.flush();
    }
}

static void finish(TResult verdict, const string& msg) {
    log_metrics();
    if (log_fs.is_open()) {
        log_fs.close();
    }
    quitf(verdict, "%s", msg.c_str());
}

void solve_test_case() {

    int n = inf.readInt();
    vector<int> a(n);
    for (int i = 0; i < n; ++i) {
        a[i] = inf.readInt();
    }

    query_limit += (2LL * n - 2);

    log_metrics();

    cout << n << endl;

    bool case_solved = false;
    while (!case_solved) {

        if (queries > HARD_CAP) {
            finish(_pe, "Hard query limit exceeded");
        }

        string token;
        if (!(cin >> token)) {
            finish(_wa, "Unexpected EOF reading token");
        }

        if (token == "!") {

            int i, j;
            if (!(cin >> i >> j)) {
                finish(_wa, "Unexpected EOF reading answer indices");
            }

            if (i < 1 || i > n || j < 1 || j > n) {
                finish(_wa, "Answer indices out of range");
            }

            if (a[i - 1] == 0 || a[j - 1] == 0) {
                case_solved = true;
            } else {
                finish(_wa, "Incorrect answer (neither index points to 0)");
            }
        } else {

            int i, j, k;

            if (token == "?") {
                if (!(cin >> i >> j >> k)) {
                    finish(_wa, "Unexpected EOF reading query indices");
                }
            } else {
                try {
                    i = stoi(token);
                } catch (...) {
                    finish(_wa, "Invalid token (expected '?' or integer): " + token);
                }
                if (!(cin >> j >> k)) {
                    finish(_wa, "Unexpected EOF reading query indices");
                }
            }

            queries++;

            if (queries % 10 == 0) log_metrics();

            bool valid = true;
            if (i < 1 || i > n || j < 1 || j > n || k < 1 || k > n) valid = false;
            if (i == j || i == k || j == k) valid = false;

            if (!valid) {
                cout << -1 << endl;
                finish(_wa, "Invalid query (indices out of range or not distinct)");
            }

            int v1 = a[i - 1];
            int v2 = a[j - 1];
            int v3 = a[k - 1];
            int mx = max({v1, v2, v3});
            int mn = min({v1, v2, v3});
            cout << (mx - mn) << endl;
        }
    }
}

int main(int argc, char** argv) {
    registerInteraction(argc, argv);

    if (argc > 2) {
        log_fs.open(argv[2], ios::out | ios::app);
    }

    atexit(log_metrics);

    int t = inf.readInt();
    cout << t << endl;

    while (t--) {
        solve_test_case();
    }

    finish(_ok, "All test cases passed");
}

#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");

    int t = opt<int>("t", 1);

    int fixed_n = opt<int>("n", 0);

    if (mode != "non" && mode != "adp") {
        quitf(_fail, "Invalid mode '%s'. Expected 'non' or 'adp'.", mode.c_str());
    }

    cout << t << endl;

    long long current_n_sum = 0;
    const int MAX_SUM_N = 3000;

    for (int i = 0; i < t; ++i) {
        int n;
        if (fixed_n > 0) {
            n = fixed_n;
        } else {

            int remaining_cases = t - i;
            long long remaining_budget = MAX_SUM_N - current_n_sum;

            long long min_needed_future = 4LL * (remaining_cases - 1);
            long long max_current = remaining_budget - min_needed_future;

            int lower = 4;
            int upper = min((long long)1000, max_current);

            if (upper < lower) {
                quitf(_fail, "Cannot generate valid n: budget exhausted or constraints impossible.");
            }

            if (t <= 20) {

                n = rnd.wnext(lower, upper, 10);
            } else {

                n = rnd.next(lower, upper);
            }
        }

        current_n_sum += n;

        if (mode == "adp") {

            cout << n << endl;
        } else {

            cout << n << endl;

            vector<int> a(n);
            int zero_pos = rnd.next(0, n - 1);

            int strategy = rnd.next(1, 100);

            if (strategy <= 30) {

                for (int k = 0; k < n; k++) {
                    if (k == zero_pos) a[k] = 0;
                    else a[k] = rnd.next(1, 1000000000);
                }
            } else if (strategy <= 60) {

                set<int> s;
                while ((int)s.size() < n - 1) {
                    s.insert(rnd.next(1, 1000000000));
                }
                vector<int> vals(s.begin(), s.end());
                shuffle(vals.begin(), vals.end());
                int idx = 0;
                for (int k = 0; k < n; k++) {
                    if (k == zero_pos) a[k] = 0;
                    else a[k] = vals[idx++];
                }
            } else if (strategy <= 80) {

                int val1 = rnd.next(1, 1000000000);
                int val2 = rnd.next(1, 1000000000);
                for (int k = 0; k < n; k++) {
                    if (k == zero_pos) a[k] = 0;
                    else a[k] = (rnd.next(0, 1) ? val1 : val2);
                }
            } else {

                int base = rnd.next(1, 999900000);
                for (int k = 0; k < n; k++) {
                    if (k == zero_pos) a[k] = 0;
                    else a[k] = base + rnd.next(0, 1000);
                }
            }

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

    return 0;
}


This is the Easy version of the problem. The difference between the versions is that in this version, you can make at most $\max(300, \lceil\frac{n}{2}\rceil+2)$ 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 $\max(300, \lceil\frac{n}{2}\rceil+2)$ 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 $\max(300, \lceil\frac{n}{2}\rceil+2)$ 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.

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long queries = 0;
static long long query_limit = 0;
static long long hard_cap = 0;

static void log_metrics() {
    try {
        tout << "queries=" << queries << endl;
        tout << "query_limit=" << query_limit << endl;
    } catch (...) {

    }
}

static void finish(TResult verdict, const string& msg) {
    log_metrics();
    quitf(verdict, "%s", msg.c_str());
}

static int mex_subarray(const vector<int>& p, int l, int r, vector<char>& used) {
    int len = r - l + 1;
    for (int i = 0; i <= len + 1; i++) used[i] = 0;
    for (int i = l; i <= r; i++) {
        int v = p[i];
        if (v <= len + 1) used[v] = 1;
    }
    for (int i = 0; ; i++) if (!used[i]) return i;
}

int main(int argc, char** argv) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    int t = inf.readInt(1, 100, "t");

    cout << t << endl;
    cout.flush();

    for (int tc = 0; tc < t; tc++) {
        int n = inf.readInt(4, 10000, "n");
        int q = inf.readInt(1, 300000, "q");

        vector<pair<int,int>> ranges(q);
        for (int i = 0; i < q; i++) {
            int l = inf.readInt(1, n, "l");
            int r = inf.readInt(l, n, "r");
            ranges[i] = {l-1, r-1};
        }

        vector<int> p(n);
        for (int i = 0; i < n; i++) {
            p[i] = inf.readInt(0, n-1, "p[i]");
        }

        long long B = max(300LL, (long long)((n + 1) / 2) + 2);
        query_limit += B;
        hard_cap = max(hard_cap, max(200000LL, 10 * B));

        log_metrics();

        cout << n << " " << q << endl;
        for (auto &rg : ranges) {
            cout << (rg.first + 1) << " " << (rg.second + 1) << endl;
        }
        cout.flush();

        vector<char> used(n + 5);
        int correct = 0;
        for (auto &rg : ranges) {
            correct = max(correct, mex_subarray(p, rg.first, rg.second, used));
        }

        while (true) {
            if (queries > hard_cap) {
                finish(_pe, "Hard cap exceeded");
            }

            string tok;
            if (!(cin >> tok)) {
                finish(_pe, "Unexpected EOF from contestant");
            }

            if (tok == "?") {
                int l, r;
                if (!(cin >> l >> r)) {
                    finish(_pe, "Malformed query");
                }
                l--; r--;
                if (l < 0 || r < l || r >= n) {
                    finish(_wa, "Query out of bounds");
                }
                int ans = mex_subarray(p, l, r, used);
                queries++;
                cout << ans << endl;
                cout.flush();
                if ((queries & 7) == 0) log_metrics();
            } else if (tok == "!") {
                int x;
                if (!(cin >> x)) {
                    finish(_pe, "Malformed answer");
                }
                if (x != correct) {
                    finish(_wa, "Wrong answer");
                }
                break;
            } else {
                int l = stoi(tok);
                int r;
                if (!(cin >> r)) {
                    finish(_pe, "Malformed query");
                }
                l--; r--;
                if (l < 0 || r < l || r >= n) {
                    finish(_wa, "Query out of bounds");
                }
                int ans = mex_subarray(p, l, r, used);
                queries++;
                cout << ans << endl;
                cout.flush();
                if ((queries & 7) == 0) log_metrics();
            }
        }
    }

    finish(_ok, "OK");
    return 0;
}

#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");

    const long long MAX_SUM_N = 10000;
    const long long MAX_SUM_Q = 300000;

    int t = -1;
    int seed = atoi(argv[1]);

    struct TestCase {
        int n, q;
    };
    vector<TestCase> cases;

    if (seed == 1) {

        t = 3;
        cases = {{4, 1}, {4, 10}, {10, 20}};
    } else if (seed == 2) {

        t = 1;
        cases = {{10000, 300000}};
    } else if (seed == 3) {

        t = 100;

    } else {

        if (rnd.next(2) == 0) t = rnd.next(1, 10);
        else t = rnd.next(10, 100);
    }

    if (cases.empty()) {
        long long budget_n = MAX_SUM_N;
        long long budget_q = MAX_SUM_Q;

        if (budget_n < t * 4LL) budget_n = t * 4LL;

        vector<long long> ns = rnd.partition(t, budget_n, 4LL);
        vector<long long> qs = rnd.partition(t, budget_q, 1LL);

        for (int i = 0; i < t; i++) {
            long long n_i = ns[i];
            long long q_i = qs[i];

            long long max_ranges = n_i * (n_i + 1) / 2;
            if (q_i > max_ranges) q_i = max_ranges;
            cases.push_back({(int)n_i, (int)q_i});
        }
    }

    println(t);
    for (const auto& tc : cases) {
        int n = tc.n;
        int q = tc.q;
        println(n, q);

        long long max_ranges = 1LL * n * (n + 1) / 2;
        vector<pair<int, int>> ranges;

        if (max_ranges <= 200000) {
            vector<pair<int, int>> all;
            all.reserve(max_ranges);
            for (int l = 1; l <= n; l++) {
                for (int r = l; r <= n; r++) {
                    all.push_back({l, r});
                }
            }
            shuffle(all.begin(), all.end());
            for (int i = 0; i < q; i++) {
                ranges.push_back(all[i]);
            }
        } else {

            set<pair<int, int>> distinct_ranges;
            while ((int)distinct_ranges.size() < q) {
                int l = rnd.next(1, n);
                int r = rnd.next(1, n);
                if (l > r) swap(l, r);
                distinct_ranges.insert({l, r});
            }
            ranges.assign(distinct_ranges.begin(), distinct_ranges.end());
            shuffle(ranges.begin(), ranges.end());
        }

        for (auto p : ranges) {
            println(p.first, p.second);
        }

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

    }
    return 0;
}


IOI 2025 - Migrations

This is an interactive problem.

The species of penguins that Blackslex is researching lives on an island that is a grid with $n$ rows and $n$ columns. Exactly one penguin lives in each one cell of the grid.

He labelled each penguin as an integer from $1$ to $n^2$. After some time, some penguins migrated to another cell. After migration, every penguin will still be in some cell on the grid, and every cell contains exactly one penguin. He needs the current position of every penguin.

To do so, he can ask a penguin how far another penguin is from it.

Formally, for a possible grid $x$ representing the position of all penguins, denote $\operatorname{dist}(x, i, j)$ as the Manhattan distance of the penguin $i$ to the penguin $j$ in $x$$^{\text{∗}}$.

There is a hidden grid $a$ with $n$ rows and $n$ columns. You need to find a grid $b$ that satisfies

* $b$ has $n$ rows and $n$ columns.
* Each cell of $b$ contains an integer from $1$ to $n^2$, which is a penguin's label. Each integer will be in a single cell.
* For all $1 \leq i, j \leq n^2$, it holds that $\operatorname{dist}(a, i, j) = \operatorname{dist}(b, i, j)$.

To do so, you may make the following query no more than $3n^2 + 150$ times.

* Given $i$, $j$ ($1 \leq i, j \leq n^2$), receive the value of $\operatorname{dist}(a, i, j)$.

$^{\text{∗}}$Let $r_i$, $c_i$ denote the row and column that the penguin $i$ is in, and denote the same for $r_j$, $c_j$, then the Manhattan distance is $|r_i - r_j| + |c_i - c_j|$.

Input

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

The first line of each test case contains a single integer $n$ ($2 \leq n \leq 100$) — the size of the island.

It is guaranteed that the total sum of all values of $n$ across all test cases does not exceed $500$.

Interaction

To ask a query, pick two integer $i$, $j$ ($1 \leq i, j \leq n^2$) and print "? $i$ $j$" (without quotes) to a line.

You will receive a single integer, which is the distance between penguins $i$ and $j$.

You may make no more than $3n^2 + 150$ queries in each test case.

After you finish your queries, output "!" in a line, then output $n$ lines, each containing $n$ integers, the $j$-th integer on the $i$-th line is $b_{i,j}$.

Your output must satisfy the conditions given, and you may output any such $b$ if multiple are possible. Note that this is not considered a query and is not taken into account when counting the number of queries asked.

After this, proceed to the next test case.

The interactor in this task is not adaptive. In other words, the grid does not change during the interaction.

If you make more than $3n^2 + 150$ queries in a test case during an interaction, your program must terminate immediately, and you will receive the Wrong Answer verdict. 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 will get Idleness limit exceeded. 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

```
2
2

1

2

1

1

2

1

3

3
```

Output

```? 1 2? 1 3? 1 4? 2 3? 2 4? 3 4!
3 4
2 1? 1 8!
9 1 3
4 2 7
8 5 6
```

Note

Note that additional lines are for ease of reading. Your solution should not output these additional lines.

In the first test case, the grid $a$ is

|  |  |
| --- | --- |
| 1 | 4 |
| 2 | 3 |

In the second test case, the grid $a$ is

|  |  |  |
| --- | --- | --- |
| 9 | 1 | 3 |
| 4 | 2 | 7 |
| 8 | 5 | 6 |

The interaction is as follows.

|  |  |  |
| --- | --- | --- |
| Contestant | Judge | Description |
|  | 2 | Start of the first test case. The island has size $n=2$. |
|? 1 2 |  | The contestant asks for the distance of penguin labelled $1$ and $2$. |
|  | 1 | The distance of penguin labelled $1$ and $2$ is $1$. |
|? 1 3 |  | The contestant asks for the distance of penguin labelled $1$ and $3$. |
|  | 2 | The distance of penguin labelled $1$ and $3$ is $2$. |
|? 1 4 |  | The contestant asks for the distance of penguin labelled $1$ and $4$. |
|  | 1 | The distance of penguin labelled $1$ and $4$ is $1$. |
|? 2 3 |  | The contestant asks for the distance of penguin labelled $2$ and $3$. |
|  | 1 | The distance of penguin labelled $2$ and $3$ is $1$. |
|? 2 4 |  | The contestant asks for the distance of penguin labelled $2$ and $4$. |
|  | 2 | The distance of penguin labelled $2$ and $4$ is $2$. |
|? 3 4 |  | The contestant asks for the distance of penguin labelled $3$ and $4$. |
|  | 1 | The distance of penguin labelled $3$ and $4$ is $1$. |
|! |  | The contestant determined a possible grid $b$. |
| 3 4 |  | Note that the grid need not be exactly the same, but it must hold that $\operatorname{dist}(a, i, j) = \operatorname{dist}(b, i, j)$ for all $1 \leq i, j \leq n^2$. |
| 2 1 |  |  |
|  | 3 | Start of the second test case. The island has size $n=3$. |
|? 1 8 |  | The contestant asks for the distance of penguin labelled $1$ and $8$. |
|  | 3 | The distance of penguin labelled $1$ and $8$ is $3$. |
|! |  | The contestant determined a possible grid $b$. |
| 9 1 3 |  |  |
| 4 2 7 |  |  |
| 8 5 6 |  |  |

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long queries = 0;
static long long query_limit = 0;

static void log_metrics() {
    try {
        tout << "queries=" << queries << endl;
        tout << "query_limit=" << query_limit << endl;
    } catch (...) {

    }
}

static void finish(TResult verdict, const string& msg) {
    log_metrics();
    quitf(verdict, "%s", msg.c_str());
}

struct TestCase {
    int n = 0;
    int n2 = 0;
    vector<int> ra, ca;
};

static pair<int,int> applyTransform(int n, int k, int r, int c) {

    switch (k) {
        case 0: return {r, c};
        case 1: return {r, n - 1 - c};
        case 2: return {n - 1 - r, c};
        case 3: return {n - 1 - r, n - 1 - c};
        case 4: return {c, r};
        case 5: return {c, n - 1 - r};
        case 6: return {n - 1 - c, r};
        case 7: return {n - 1 - c, n - 1 - r};
        default: return {r, c};
    }
}

int main(int argc, char** argv) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 0;
    try {
        t = inf.readInt(1, 200, "t");
    } catch (...) {
        query_limit = 0;
        log_metrics();
        finish(_pe, "Failed to read t from hidden input");
    }

    vector<TestCase> tests;
    tests.reserve(t);

    long long totalLimit = 0;
    for (int tc = 0; tc < t; ++tc) {
        TestCase cs;
        cs.n = inf.readInt(2, 100, "n");
        cs.n2 = cs.n * cs.n;
        cs.ra.assign(cs.n2 + 1, -1);
        cs.ca.assign(cs.n2 + 1, -1);

        vector<char> seen(cs.n2 + 1, 0);
        for (int r = 0; r < cs.n; ++r) {
            for (int c = 0; c < cs.n; ++c) {
                int x = inf.readInt(1, cs.n2, "grid_label");
                if (seen[x]) {
                    query_limit = 0;
                    log_metrics();
                    finish(_pe, "Hidden input is not a permutation");
                }
                seen[x] = 1;
                cs.ra[x] = r;
                cs.ca[x] = c;
            }
        }

        totalLimit += 3LL * cs.n2 + 150;
        tests.push_back(std::move(cs));
    }

    query_limit = totalLimit;
    log_metrics();

    const long long hard_cap = max(200000LL, 10LL * query_limit);

    cout << t << endl;
    for (int tc = 0; tc < t; ++tc) {
        const TestCase& cs = tests[tc];
        cout << cs.n << endl;

        while (true) {
            string cmd;
            if (!(cin >> cmd)) {
                finish(_pe, "Unexpected EOF from contestant");
            }

            if (cmd == "?") {
                long long i_ll, j_ll;
                if (!(cin >> i_ll >> j_ll)) {
                    finish(_pe, "Malformed query: expected two integers after '?'");
                }
                if (i_ll < 1 || i_ll > cs.n2 || j_ll < 1 || j_ll > cs.n2) {
                    finish(_pe, "Query indices out of range");
                }
                int i = (int)i_ll, j = (int)j_ll;

                ++queries;
                if (queries > hard_cap) {
                    finish(_pe, "Hard cap exceeded (possible infinite loop / spam)");
                }

                int d = abs(cs.ra[i] - cs.ra[j]) + abs(cs.ca[i] - cs.ca[j]);
                cout << d << endl;
            } else if (cmd == "!") {
                vector<int> rb(cs.n2 + 1, -1), cb(cs.n2 + 1, -1);
                vector<char> seen(cs.n2 + 1, 0);

                for (int r = 0; r < cs.n; ++r) {
                    for (int c = 0; c < cs.n; ++c) {
                        long long x_ll;
                        if (!(cin >> x_ll)) {
                            finish(_pe, "Malformed answer: not enough grid integers after '!'");
                        }
                        if (x_ll < 1 || x_ll > cs.n2) {
                            finish(_wa, "Answer contains label out of range");
                        }
                        int x = (int)x_ll;
                        if (seen[x]) {
                            finish(_wa, "Answer grid is not a permutation (duplicate label)");
                        }
                        seen[x] = 1;
                        rb[x] = r;
                        cb[x] = c;
                    }
                }

                bool ok = false;
                for (int k = 0; k < 8 && !ok; ++k) {
                    bool good = true;
                    for (int label = 1; label <= cs.n2; ++label) {
                        auto [tr, tc2] = applyTransform(cs.n, k, cs.ra[label], cs.ca[label]);
                        if (rb[label] != tr || cb[label] != tc2) {
                            good = false;
                            break;
                        }
                    }
                    if (good) ok = true;
                }

                if (!ok) {
                    finish(_wa, "Answer grid does not preserve all pairwise Manhattan distances");
                }
                break;
            } else {
                finish(_pe, "Invalid command token (expected '?' or '!')");
            }
        }
    }

    finish(_ok, "OK");
    return 0;
}

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static void fyShuffle(vector<int>& a) {
    for (int i = (int)a.size() - 1; i > 0; --i) {
        int j = rnd.next(0, i);
        swap(a[i], a[j]);
    }
}

static vector<int> buildCellOrder(int n, int pattern) {
    vector<int> order;
    order.reserve(n * n);

    auto pushCell = [&](int r, int c) {
        order.push_back(r * n + c);
    };

    if (pattern == 0) {
        for (int r = 0; r < n; ++r)
            for (int c = 0; c < n; ++c)
                pushCell(r, c);
        return order;
    }

    if (pattern == 1) {
        for (int r = 0; r < n; ++r) {
            if (r % 2 == 0) {
                for (int c = 0; c < n; ++c) pushCell(r, c);
            } else {
                for (int c = n - 1; c >= 0; --c) pushCell(r, c);
            }
        }
        return order;
    }

    if (pattern == 2) {
        int b = rnd.next(5, 15);
        int br = (n + b - 1) / b;
        int bc = (n + b - 1) / b;
        vector<int> blocks;
        blocks.reserve(br * bc);
        for (int r = 0; r < br; ++r)
            for (int c = 0; c < bc; ++c)
                blocks.push_back(r * bc + c);
        fyShuffle(blocks);

        for (int id : blocks) {
            int r0 = (id / bc) * b;
            int c0 = (id % bc) * b;
            int r1 = min(n, r0 + b);
            int c1 = min(n, c0 + b);

            vector<int> local;
            local.reserve((r1 - r0) * (c1 - c0));
            for (int r = r0; r < r1; ++r) {
                if ((r - r0) % 2 == 0) {
                    for (int c = c0; c < c1; ++c) local.push_back(r * n + c);
                } else {
                    for (int c = c1 - 1; c >= c0; --c) local.push_back(r * n + c);
                }
            }
            if (rnd.next(0, 1) == 1) fyShuffle(local);
            order.insert(order.end(), local.begin(), local.end());
        }
        return order;
    }

    int top = 0, left = 0, bottom = n - 1, right = n - 1;
    while (top <= bottom && left <= right) {
        for (int c = left; c <= right; ++c) pushCell(top, c);
        for (int r = top + 1; r <= bottom; ++r) pushCell(r, right);
        if (top != bottom) {
            for (int c = right - 1; c >= left; --c) pushCell(bottom, c);
        }
        if (left != right) {
            for (int r = bottom - 1; r > top; --r) pushCell(r, left);
        }
        ++top; ++left; --bottom; --right;
    }

    int swaps = min((int)order.size() / 20, 500);
    for (int k = 0; k < swaps; ++k) {
        int i = rnd.next(0, (int)order.size() - 1);
        int j = rnd.next(0, (int)order.size() - 1);
        swap(order[i], order[j]);
    }
    return order;
}

static vector<int> buildGridNon(int n, long long seedValue) {
    vector<int> grid(n * n, 0);

    if (seedValue == 1) {

        if (n == 2) {

            grid = {1, 4, 3, 2};
            return grid;
        }
    }
    if (seedValue == 2) {
        if (n == 3) {

            grid = {9, 1, 7,
                    2, 5, 8,
                    6, 3, 4};
            return grid;
        }
    }
    if (seedValue == 3) {

    }

    int pattern = (seedValue == 3) ? 2 : (int)(seedValue % 4);
    vector<int> cellOrder = buildCellOrder(n, pattern);

    vector<int> labels(n * n);
    iota(labels.begin(), labels.end(), 1);

    int stylePick = (seedValue == 3) ? 1 : rnd.next(0, 2);

    if (stylePick == 0) {
        fyShuffle(labels);
        for (int k = 0; k < n * n; ++k) grid[cellOrder[k]] = labels[k];
        return grid;
    }

    if (stylePick == 1) {

        vector<int> pairs;
        pairs.reserve(n * n);
        vector<char> used(n * n, 0);
        for (int idx = 0; idx < n * n; ++idx) {
            if (used[idx]) continue;
            int r = idx / n, c = idx % n;
            int sidx = (n - 1 - r) * n + (n - 1 - c);
            used[idx] = 1;
            used[sidx] = 1;

            pairs.push_back(idx);
            if (sidx != idx) pairs.push_back(sidx);
        }

        int m = (int)pairs.size();
        int hasSingleton = (m % 2);
        int pairCount = (m - hasSingleton) / 2;
        vector<int> perm(pairCount);
        iota(perm.begin(), perm.end(), 0);
        fyShuffle(perm);

        vector<int> cellSeq;
        cellSeq.reserve(m);
        for (int id : perm) {
            int a = pairs[2 * id];
            int b = pairs[2 * id + 1];
            if (rnd.next(0, 1) == 1) swap(a, b);
            cellSeq.push_back(a);
            cellSeq.push_back(b);
        }
        if (hasSingleton) cellSeq.push_back(pairs[m - 1]);

        fyShuffle(labels);

        int ptr = 0;
        for (int idx : cellSeq) {
            grid[idx] = labels[ptr++];
        }

        vector<int> remapped(n * n, 0);
        for (int k = 0; k < n * n; ++k) {
            remapped[cellOrder[k]] = grid[k];
        }
        return remapped;
    }

    int disruptions = max(10, (n * n) / 25);
    for (int t = 0; t < disruptions; ++t) {
        int i = rnd.next(0, n * n - 1);
        int j = rnd.next(0, n * n - 1);
        swap(labels[i], labels[j]);
    }
    for (int k = 0; k < n * n; ++k) grid[cellOrder[k]] = labels[k];
    return grid;
}

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

    long long seedValue = 1;
    if (argc > 1) seedValue = atoll(argv[1]);

    string mode = opt<string>("mode", "non");
    int nOpt = opt<int>("n", -1);

    int n;
    if (nOpt != -1) {
        n = nOpt;
    } else {
        if (seedValue == 1) n = 2;
        else if (seedValue == 2) n = 3;
        else if (seedValue == 3) n = 100;
        else n = rnd.next(80, 100);
    }

    if (n < 2) n = 2;
    if (n > 100) n = 100;

    if (mode == "adp") {

        cout << 1 << "\n";
        cout << n << "\n";
        return 0;
    }

    if (mode != "non") {
        quitf(_fail, "unknown mode: %s", mode.c_str());
    }

    vector<int> grid = buildGridNon(n, seedValue);

    cout << 1 << "\n";
    cout << n << "\n";
    for (int r = 0; r < n; ++r) {
        for (int c = 0; c < n; ++c) {
            if (c) cout << ' ';
            cout << grid[r * n + c];
        }
        cout << "\n";
    }
    return 0;
}


Ray lost his array and needs to find it by asking Omkar. Omkar is willing to disclose that the array has the following qualities:

1. The array has $n$ ($1 \le n \le 2 \cdot 10^5$) elements.
2. Every element in the array $a_i$ is an integer in the range $1 \le a_i \le 10^9.$
3. The array is sorted in nondecreasing order.

Ray is allowed to send Omkar a series of queries. A query consists of two integers, $l$ and $r$ such that $1 \le l \le r \le n$. Omkar will respond with two integers, $x$ and $f$. $x$ is the mode of the subarray from index $l$ to index $r$ inclusive. The mode of an array is defined by the number that appears the most frequently. If there are multiple numbers that appear the most number of times, the smallest such number is considered to be the mode. $f$ is the amount of times that $x$ appears in the queried subarray.

The array has $k$ ($1 \le k \le \min(25000,n)$) distinct elements. However, due to Ray's sins, Omkar will not tell Ray what $k$ is. Ray is allowed to send at most $4k$ queries.

Help Ray find his lost array.

Input

The only line of the input contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$), which equals to the length of the array that you are trying to find.

Interaction

The interaction starts with reading $n$.

Then you can make one type of query:

* "$? \enspace l \enspace r$" ($1 \le l \le r \le n$) where $l$ and $r$ are the bounds of the subarray that you wish to query.

The answer to each query will be in the form "$x \enspace f$" where $x$ is the mode of the subarray and $f$ is the number of times $x$ appears in the subarray.

* $x$ satisfies ($1 \leq x \leq 10^9$).
* $f$ satisfies ($1 \leq f \leq r-l+1$).
* If you make more than $4k$ queries or violate the number range in the query, you will get an output "-1."
* If you terminate after receiving the response "$-1$", you will get the "Wrong answer" verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.

To output your answer, print:

* "$! \enspace a_1 \enspace a_2 \enspace \ldots \enspace a_{n-1} \enspace a_n$" which is an exclamation point followed by the array with a space between every element.

And quit after that. This query is not counted towards the $4k$ queries limit.

After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. 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 documentation for other languages.

Example

Input

```
6

2 2

2 2

3 2

2 1
```

Output

```
? 1 6

? 1 3

? 4 6

? 3 4

! 1 2 2 3 3 4
```

Note

The first query is $l=1$ and $r=6$. The mode is $2$, and $2$ appears $2$ times, so $x=2$ and $f=2$. Note that $3$ also appears two times, but $2$ is outputted because $2$ is smaller.

The second query is $l=1$ and $r=3$. The mode is $2$ and $2$ appears twice in the subarray with indices $[1,3]$.

The third query is $l=4$ and $r=6$. The mode is $3$ and $3$ appears twice in the subarray with indices $[4,6]$.

The fourth query is $l=3$ and $r=4$. The mode is $2$, which appears once in the subarray with indices $[3,4]$. Note that $3$ also appears once in that range, but $2$ is smaller than $3$.

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long queries = 0;
static long long query_limit = 0;

static void log_metrics() {
    try {
        tout << "queries=" << queries << "\n";
        tout << "query_limit=" << query_limit << "\n";
        tout.flush();
    } catch (...) {

    }
}

static void finish(TResult verdict, const string& msg) {
    log_metrics();
    quitf(verdict, "%s", msg.c_str());
}

static bool parseLongLong(const string& s, long long& out) {
    if (s.empty()) return false;
    int i = 0;
    bool neg = false;
    if (s[i] == '-') {
        neg = true;
        i++;
        if (i == (int)s.size()) return false;
    }
    long long val = 0;
    for (; i < (int)s.size(); i++) {
        char c = s[i];
        if (c < '0' || c > '9') return false;
        int d = c - '0';
        if (val > (LLONG_MAX - d) / 10) return false;
        val = val * 10 + d;
    }
    out = neg ? -val : val;
    return true;
}

static inline pair<int,int> combineBest(const pair<int,int>& a, const pair<int,int>& b) {
    if (a.first != b.first) return (a.first > b.first) ? a : b;
    return (a.second < b.second) ? a : b;
}

int main(int argc, char** argv) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    int n = inf.readInt(1, 200000, "n");
    vector<long long> a(n + 1);
    for (int i = 1; i <= n; i++) {
        a[i] = inf.readLong(1LL, 1000000000LL, ("a[" + to_string(i) + "]").c_str());
        if (i > 1 && a[i] < a[i - 1]) {
            finish(_fail, "Hidden array is not nondecreasing.");
        }
    }

    vector<int> gid(n + 1, -1);
    vector<int> L, R, len;
    vector<long long> val;
    L.reserve(n);
    R.reserve(n);
    len.reserve(n);
    val.reserve(n);

    int m = 0;
    for (int i = 1; i <= n; ) {
        int j = i;
        while (j <= n && a[j] == a[i]) j++;
        int l = i, r = j - 1;
        int cnt = r - l + 1;
        val.push_back(a[i]);
        L.push_back(l);
        R.push_back(r);
        len.push_back(cnt);
        for (int t = l; t <= r; t++) gid[t] = m;
        m++;
        i = j;
    }

    query_limit = 4LL * m;
    long long hard_cap = max(200000LL, 10LL * query_limit);

    vector<int> lg(m + 1, 0);
    for (int i = 2; i <= m; i++) lg[i] = lg[i / 2] + 1;
    int K = (m == 0) ? 1 : (lg[m] + 1);
    vector<vector<pair<int,int>>> st(K, vector<pair<int,int>>(m));
    for (int i = 0; i < m; i++) st[0][i] = {len[i], i};
    for (int k = 1; k < K; k++) {
        int span = 1 << k;
        int half = span >> 1;
        for (int i = 0; i + span <= m; i++) {
            st[k][i] = combineBest(st[k - 1][i], st[k - 1][i + half]);
        }
    }

    auto rmq = [&](int l, int r) -> pair<int,int> {

        int length = r - l + 1;
        int k = lg[length];
        int span = 1 << k;
        return combineBest(st[k][l], st[k][r - span + 1]);
    };

    cout << n << "\n";
    cout.flush();

    log_metrics();

    while (true) {
        string cmd;
        if (!(cin >> cmd)) {
            finish(_wa, "EOF from contestant before final answer.");
        }

        if (cmd == "?") {
            string sl, sr;
            if (!(cin >> sl >> sr)) {
                cout << "-1\n";
                cout.flush();
                finish(_pe, "Malformed query: expected two integers after '?'.");
            }
            long long lll, rll;
            if (!parseLongLong(sl, lll) || !parseLongLong(sr, rll)) {
                cout << "-1\n";
                cout.flush();
                finish(_pe, "Malformed query: l/r are not valid integers.");
            }

            queries++;
            if (queries > hard_cap) {
                cout << "-1\n";
                cout.flush();
                finish(_pe, "Hard cap exceeded (too many queries).");
            }

            if (lll < 1 || rll < 1 || lll > rll || rll > n) {
                cout << "-1\n";
                cout.flush();
                finish(_wa, "Query out of bounds.");
            }

            int l = (int)lll;
            int r = (int)rll;

            int gl = gid[l];
            int gr = gid[r];
            long long x, f;

            if (gl == gr) {
                x = val[gl];
                f = (long long)(r - l + 1);
            } else {
                long long leftPart = (long long)(R[gl] - l + 1);
                long long rightPart = (long long)(r - L[gr] + 1);

                long long bestFreq = leftPart;
                int bestIdx = gl;

                if (rightPart > bestFreq || (rightPart == bestFreq && gr < bestIdx)) {
                    bestFreq = rightPart;
                    bestIdx = gr;
                }

                if (gl + 1 <= gr - 1) {
                    auto mid = rmq(gl + 1, gr - 1);
                    long long midFreq = mid.first;
                    int midIdx = mid.second;
                    if (midFreq > bestFreq || (midFreq == bestFreq && midIdx < bestIdx)) {
                        bestFreq = midFreq;
                        bestIdx = midIdx;
                    }
                }

                x = val[bestIdx];
                f = bestFreq;
            }

            cout << x << " " << f << "\n";
            cout.flush();
        } else if (cmd == "!") {
            vector<long long> out(n + 1, 0);
            for (int i = 1; i <= n; i++) {
                string s;
                if (!(cin >> s)) {
                    finish(_pe, "Final answer incomplete: not enough numbers.");
                }
                long long v;
                if (!parseLongLong(s, v)) {
                    finish(_pe, "Final answer contains a non-integer token.");
                }
                out[i] = v;
            }
            for (int i = 1; i <= n; i++) {
                if (out[i] != a[i]) {
                    finish(_wa, "Final answer is incorrect.");
                }
            }
            finish(_ok, "OK");
        } else {
            cout << "-1\n";
            cout.flush();
            finish(_pe, "Unknown command token (expected '?' or '!').");
        }
    }
}

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long queries = 0;
static long long query_limit = 0;

static void log_metrics() {
    try {
        tout << "queries=" << queries << "\n";
        tout << "query_limit=" << query_limit << "\n";
        tout.flush();
    } catch (...) {

    }
}

static void finish(TResult verdict, const string& msg) {
    log_metrics();
    quitf(verdict, "%s", msg.c_str());
}

struct ModeQueryDS {
    int n = 0;
    vector<long long> a;
    int K = 0;
    vector<long long> val;
    vector<int> stPos;
    vector<int> enPos;
    vector<int> len;
    vector<int> pos2block;

    vector<int> lg2;
    vector<vector<pair<int,int>>> st;

    void build_from_array(int n_, const vector<long long>& arr1indexed) {
        n = n_;
        a = arr1indexed;
        if ((int)a.size() != n + 1) a.assign(n + 1, 0);

        val.clear();
        stPos.clear();
        enPos.clear();
        len.clear();
        pos2block.assign(n + 1, 0);

        if (n == 0) {
            K = 0;
            return;
        }

        int cur = -1;
        for (int i = 1; i <= n; i++) {
            if (i == 1 || a[i] != a[i - 1]) {
                if (cur != -1) {
                    enPos[cur] = i - 1;
                    len[cur] = enPos[cur] - stPos[cur] + 1;
                }
                cur++;
                val.push_back(a[i]);
                stPos.push_back(i);
                enPos.push_back(i);
                len.push_back(1);
            }
            pos2block[i] = cur;
        }
        if (cur >= 0) {
            enPos[cur] = n;
            len[cur] = enPos[cur] - stPos[cur] + 1;
        }
        K = cur + 1;

        build_sparse();
    }

    void build_sparse() {
        if (K <= 0) return;
        lg2.assign(K + 1, 0);
        for (int i = 2; i <= K; i++) lg2[i] = lg2[i / 2] + 1;
        int P = lg2[K] + 1;
        st.assign(P, {});
        st[0].resize(K);
        for (int i = 0; i < K; i++) st[0][i] = {len[i], -i};
        for (int j = 1; j < P; j++) {
            int span = 1 << j;
            int half = span >> 1;
            int lim = K - span + 1;
            st[j].resize(max(0, lim));
            for (int i = 0; i < lim; i++) {
                st[j][i] = max(st[j - 1][i], st[j - 1][i + half]);
            }
        }
    }

    int rmq_best_block(int L, int R) const {

        int lenRange = R - L + 1;
        int j = lg2[lenRange];
        int span = 1 << j;
        auto p1 = st[j][L];
        auto p2 = st[j][R - span + 1];
        auto best = max(p1, p2);
        return -best.second;
    }

    pair<long long, long long> query_mode(int l, int r) const {
        int bL = pos2block[l];
        int bR = pos2block[r];
        if (bL == bR) {
            return {val[bL], (long long)r - l + 1};
        }
        long long leftFreq = (long long)enPos[bL] - l + 1;
        long long rightFreq = (long long)r - stPos[bR] + 1;

        long long internalFreq = 0;
        long long internalVal = (long long)4e18;
        if (bL + 1 <= bR - 1) {
            int idx = rmq_best_block(bL + 1, bR - 1);
            internalFreq = len[idx];
            internalVal = val[idx];
        }

        long long mx = max(leftFreq, max(rightFreq, internalFreq));
        long long x = (long long)4e18;
        if (leftFreq == mx) x = min(x, val[bL]);
        if (rightFreq == mx) x = min(x, val[bR]);
        if (internalFreq == mx) x = min(x, internalVal);
        return {x, mx};
    }
};

static bool readToken(string& s) {
    return (cin >> s) ? true : false;
}

static bool readLL(long long& x) {
    return (cin >> x) ? true : false;
}

int main(int argc, char** argv) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    int n = inf.readInt(1, 200000, "n");
    vector<long long> rest;
    while (!inf.seekEof()) {
        rest.push_back(inf.readLong());
    }

    bool is_adp = false;
    vector<long long> a1(n + 1, 0);

    if (rest.empty()) {

        is_adp = true;
        long long kMax = min(25000, n);
        long long vmin = 1, vmax = 1000000000LL;
        long long range = vmax - vmin + 1;
        long long k = min<long long>(kMax, min<long long>(n, range));
        if (k < 1) k = 1;

        long long base = n / k, rem = n % k;
        long long step = (k == 1) ? 0 : (vmax - vmin) / (k - 1);
        if (k > 1 && step < 1) step = 1;

        int pos = 1;
        for (int i = 0; i < (int)k; i++) {
            long long cnt = base + (i < rem ? 1 : 0);
            long long v = vmin + step * i;
            for (int t = 0; t < cnt; t++) a1[pos++] = v;
        }
        if (pos != n + 1) finish(_pe, "internal: constructed array length mismatch");
    } else if ((int)rest.size() == 3) {
        is_adp = true;
        long long kMax = rest[0];
        long long vmin = rest[1];
        long long vmax = rest[2];
        if (!(1 <= kMax && kMax <= 25000)) finish(_pe, "bad kMax in adaptive input");
        if (!(1 <= vmin && vmin <= 1000000000LL)) finish(_pe, "bad vmin in adaptive input");
        if (!(1 <= vmax && vmax <= 1000000000LL)) finish(_pe, "bad vmax in adaptive input");
        if (vmin > vmax) finish(_pe, "adaptive input: vmin>vmax");

        long long range = vmax - vmin + 1;
        long long k = min<long long>(kMax, min<long long>(n, range));
        if (k < 1) k = 1;

        long long base = n / k, rem = n % k;

        long long step = (k == 1) ? 0 : (vmax - vmin) / (k - 1);
        if (k > 1 && step < 1) step = 1;

        int pos = 1;
        for (int i = 0; i < (int)k; i++) {
            long long cnt = base + (i < rem ? 1 : 0);
            long long v = vmin + step * i;
            if (v < vmin || v > vmax) finish(_pe, "internal: value out of bounds in construction");
            for (int t = 0; t < cnt; t++) a1[pos++] = v;
        }
        if (pos != n + 1) finish(_pe, "internal: constructed array length mismatch");
    } else if ((int)rest.size() == n) {
        is_adp = false;
        for (int i = 1; i <= n; i++) {
            long long v = rest[i - 1];
            if (!(1 <= v && v <= 1000000000LL)) finish(_pe, "bad array value in non-adaptive input");
            a1[i] = v;
            if (i > 1 && a1[i] < a1[i - 1]) finish(_pe, "array not nondecreasing in non-adaptive input");
        }
    } else {
        finish(_pe, "bad input schema: expected 3 params (adp) or n values (non)");
    }

    ModeQueryDS ds;
    ds.build_from_array(n, a1);
    int kDistinct = ds.K;
    if (kDistinct <= 0) finish(_pe, "internal: K=0");

    query_limit = 4LL * (long long)kDistinct;

    log_metrics();

    cout << n << '\n';
    cout.flush();

    long long hard_cap = max(200000LL, 10LL * max(1LL, query_limit));

    while (true) {
        string cmd;
        if (!readToken(cmd)) {
            finish(_wa, "contestant terminated without final answer");
        }

        if (cmd == "?") {
            long long lll, rrr;
            if (!readLL(lll) || !readLL(rrr)) finish(_pe, "cannot read l r");
            if (lll < 1 || rrr < 1 || lll > rrr || rrr > n) finish(_pe, "query indices out of range");
            int l = (int)lll, r = (int)rrr;

            queries++;
            if (queries > hard_cap) finish(_pe, "too many queries (hard cap exceeded)");

            auto ans = ds.query_mode(l, r);
            long long x = ans.first;
            long long f = ans.second;
            if (!(1 <= x && x <= 1000000000LL)) finish(_pe, "internal: answered x out of range");
            if (!(1 <= f && f <= (r - l + 1))) finish(_pe, "internal: answered f out of range");

            cout << x << ' ' << f << '\n';
            cout.flush();
        } else if (cmd == "!") {
            vector<long long> out(n + 1, 0);
            for (int i = 1; i <= n; i++) {
                long long v;
                if (!readLL(v)) finish(_wa, "could not read full final array");
                out[i] = v;
            }
            for (int i = 1; i <= n; i++) {
                if (out[i] != a1[i]) {
                    finish(_wa, "final array mismatch");
                }
            }
            finish(_ok, "OK");
        } else {
            finish(_pe, "unknown command token");
        }
    }
}

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long pickGap(long long remaining, int groupsLeft, bool heavyTail) {

    long long minNeed = groupsLeft;
    long long maxHere = remaining - (minNeed - 1);
    if (maxHere <= 1) return 1;
    if (!heavyTail) {

        long long up = min<long long>(maxHere, 50);
        return rnd.next(1LL, up);
    } else {

        int roll = rnd.next(1, 100);
        if (roll <= 75) {
            long long up = min<long long>(maxHere, 3);
            return rnd.next(1LL, up);
        } else if (roll <= 92) {
            long long up = min<long long>(maxHere, 200);
            return rnd.next(1LL, up);
        } else {
            return rnd.next(1LL, maxHere);
        }
    }
}

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

    string mode = opt<string>("mode", "non");

    if (mode != "non" && mode != "adp") mode = "non";

    long long seed = 1;
    if (argc >= 2) {

        seed = atoll(argv[1]);
        if (seed <= 0) seed = 1;
    }

    if (mode == "adp") {

        int n;
        int kMax = opt<int>("kmax", 25000);
        int valueMin = opt<int>("vmin", 1);
        int valueMax = opt<int>("vmax", 1000000000);

        if (seed == 1) {
            n = 1;
            kMax = 1;
        } else if (seed == 2) {
            n = 200000;
            kMax = 25000;
        } else if (seed == 3) {
            n = 200000;
            kMax = 25000;
        } else {

            int roll = rnd.next(1, 100);
            if (roll <= 80) n = 200000;
            else n = rnd.next(1, 200000);
            kMax = min(kMax, min(25000, n));
        }

        cout << n << "\n" << kMax << " " << valueMin << " " << valueMax << "\n";
        return 0;
    }

    int n = opt<int>("n", 200000);
    n = max(1, min(200000, n));

    vector<long long> a;
    a.reserve(n);

    if (seed == 1) {

        n = 1;
        a.push_back(1);
    } else if (seed == 2) {

        n = 200000;
        int k = 25000;

        long long base = 1000000;
        for (int i = 0; i < k - 1; i++) a.push_back(base + i);
        long long lastVal = base + (k - 1);
        while ((int)a.size() < n) a.push_back(lastVal);
    } else if (seed == 3) {

        n = 200000;
        int k = 25000;

        vector<int> cnt(k, 8);
        long long total = 0;
        for (int c : cnt) total += c;

        int idx = 0;
        while (total < n) {
            cnt[idx % k] += 1;
            total++;
            idx++;
        }
        while (total > n) {
            int j = (idx % k);
            if (cnt[j] > 1) { cnt[j]--; total--; }
            idx++;
        }
        long long base = 500000000;
        for (int i = 0; i < k; i++) {
            for (int t = 0; t < cnt[i]; t++) a.push_back(base + i);
        }
    } else {

        int rollN = rnd.next(1, 100);
        if (rollN <= 75) n = 200000;
        else n = rnd.next(1, 200000);

        int kCap = min(25000, n);
        int k;
        int rollK = rnd.next(1, 100);
        if (rollK <= 70) k = kCap;
        else if (rollK <= 90) k = max(1, kCap - rnd.next(0, min(1000, kCap - 1)));
        else k = rnd.next(1, kCap);

        vector<int> cnt(k, 1);
        long long remaining = n;
        for (int i = 0; i < k; i++) {
            int groupsLeft = k - i;
            bool heavyTail = true;
            long long take = pickGap(remaining, groupsLeft, heavyTail);
            cnt[i] = (int)take;
            remaining -= take;
        }

        long long sum = 0;
        for (int c : cnt) sum += c;
        if (sum != n) {

            cnt.back() += (int)(n - sum);
            if (cnt.back() < 1) cnt.back() = 1;

            sum = 0;
            for (int c : cnt) sum += c;
            while (sum > n) {
                for (int i = k - 1; i >= 0 && sum > n; i--) {
                    if (cnt[i] > 1) { cnt[i]--; sum--; }
                }
            }
            while (sum < n) {
                cnt.back()++; sum++;
            }
        }

        if (k >= 10 && n >= 50) {
            int pairs = min(k / 5, 3000);
            for (int t = 0; t < pairs; t++) {
                int i = rnd.next(0, k - 2);
                int m = min(cnt[i], cnt[i + 1]);
                if (m > 1) {
                    int target = rnd.next(1, m);

                    int delta1 = cnt[i] - target;
                    int delta2 = cnt[i + 1] - target;
                    if (target >= 1 && cnt.back() + delta1 + delta2 > 0) {
                        cnt[i] = target;
                        cnt[i + 1] = target;
                        cnt.back() += (delta1 + delta2);
                    }
                }
            }
        }

        long long s2 = 0;
        for (int &c : cnt) { c = max(1, c); s2 += c; }
        if (s2 != n) {
            cnt.back() += (int)(n - s2);
            if (cnt.back() < 1) cnt.back() = 1;
        }

        long long s3 = 0;
        for (int c : cnt) s3 += c;
        while (s3 > n) {
            for (int i = k - 1; i >= 0 && s3 > n; i--) {
                if (cnt[i] > 1) { cnt[i]--; s3--; }
            }
        }
        while (s3 < n) { cnt.back()++; s3++; }

        long long v = rnd.next(1LL, 1000000000LL - (long long)k - 5);
        for (int i = 0; i < k; i++) {
            long long step;
            int rs = rnd.next(1, 100);
            if (rs <= 70) step = rnd.next(1LL, 3LL);
            else if (rs <= 95) step = rnd.next(4LL, 1000LL);
            else step = rnd.next(1001LL, 100000LL);
            v += step;
            if (v > 1000000000LL - (k - i - 1)) v = 1000000000LL - (k - i - 1);
            for (int t = 0; t < cnt[i]; t++) a.push_back(v);
        }

        if ((int)a.size() > n) a.resize(n);
        while ((int)a.size() < n) a.push_back(a.empty() ? 1 : a.back());
    }

    cout << n << "\n";
    for (int i = 0; i < n; i++) {
        if (i) cout << ' ';
        cout << a[i];
    }
    cout << "\n";
    return 0;
}


This is an interactive problem.

When data becomes too large and no longer fits on a single server, it must be sharded. Consider a system for storing user posts distributed across $S$ servers, numbered starting from one. Each time a user writes a post, it is assigned a unique identifier ranging from $1$ to $10^{18}$ and saved to a random server. The later a post was created, the larger its $id$. Sometimes posts are deleted, so servers may contain significantly different numbers of posts.

Consider all undeleted post $id$s for a user and sort them in ascending order. You want to find the $k$-th smallest identifier among them. To do this, you can send no more than 100 additional queries. Each query has the format "? $i$ $j$". In response, you will receive the identifier of the $j$-th smallest post among those stored on the $i$-th server. When you believe you know the $k$-th smallest identifier, instead of a query, you must output the answer in the format "! $id$".

Interaction Protocol

The first line contains two integers $n$ and $S$ ($1 \le n \le 100, 1 \le S \le 5$) — the number of users for whom the problem must be solved independently, and the number of servers where the posts are stored.

Next, you must solve the problem $n$ times. At the beginning of each case, read $S$ integers $a_1, a_2, \dots, a_S$ ($0 \le a_i; \sum a_i \le 10^5$) — the number of posts the user has on each server. The next line will contain the integer $k$ ($1 \le k \le \sum a_i $) — the rank of the post identifier you need to find.

Then, perform no more than 100 queries in the format described in the problem statement.

Note that the limit on the number of queries applies to each user separately; the query counter is reset when moving to the next test case.

Example

Input
```
1 2
3 2
3

3

5

10
```

Output
```
? 1 2

? 2 1

? 1 3

! 5
```

Note
In the example, the first server stores posts with $id$s 1, 3, and 10. The second server stores 5 and 7. You need to find the 3rd smallest number, which is 5.

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static long long queries = 0;
static long long query_limit = 0;

static void log_metrics() {
    try {
        tout << "queries=" << queries << "\n";
        tout << "query_limit=" << query_limit << "\n";
        tout.flush();
    } catch (...) {

    }
}

static void finish(TResult verdict, const string& msg) {
    log_metrics();
    quitf(verdict, "%s", msg.c_str());
}

struct PQNode {
    long long val;
    int s;
    int pos;
};
struct PQCmp {
    bool operator()(const PQNode& a, const PQNode& b) const {
        if (a.val != b.val) return a.val > b.val;
        if (a.s != b.s) return a.s > b.s;
        return a.pos > b.pos;
    }
};

static long long kthSmallestMerge(const vector<vector<long long>>& ids, long long k) {
    priority_queue<PQNode, vector<PQNode>, PQCmp> pq;
    long long total = 0;
    for (int i = 0; i < (int)ids.size(); i++) {
        total += (long long)ids[i].size();
        if (!ids[i].empty()) pq.push({ids[i][0], i, 0});
    }
    if (k < 1 || k > total) return -1;

    long long last = -1;
    for (long long t = 0; t < k; t++) {
        if (pq.empty()) return -1;
        auto cur = pq.top();
        pq.pop();
        last = cur.val;
        int np = cur.pos + 1;
        if (np < (int)ids[cur.s].size()) {
            pq.push({ids[cur.s][np], cur.s, np});
        }
    }
    return last;
}

int main(int argc, char** argv) {
    registerInteraction(argc, argv);
    atexit(log_metrics);

    int n = inf.readInt(1, 100, "n");
    int S = inf.readInt(1, 5, "S");

    query_limit = 100LL * (long long)n;
    const long long hard_cap = max(200000LL, 10LL * query_limit);

    log_metrics();

    cout << n << " " << S << endl;

    for (int tc = 0; tc < n; tc++) {
        vector<int> a(S, 0);
        long long total = 0;
        for (int i = 0; i < S; i++) {
            a[i] = inf.readInt(0, 100000, "a_i");
            total += a[i];
        }
        if (total <= 0) finish(_pe, "Hidden input invalid: total posts is zero");
        if (total > 100000) finish(_pe, "Hidden input invalid: total posts too large");

        long long k = inf.readLong(1, total, "k");

        vector<vector<long long>> ids(S);
        for (int i = 0; i < S; i++) {
            ids[i].resize(a[i]);
            for (int j = 0; j < a[i]; j++) {
                long long x = inf.readLong(1LL, 1000000000000000000LL, "id");
                ids[i][j] = x;
            }
        }

        long long correct = kthSmallestMerge(ids, k);
        if (correct < 0) finish(_pe, "Failed to compute correct answer from hidden input");

        for (int i = 0; i < S; i++) {
            if (i) cout << ' ';
            cout << a[i];
        }
        cout << endl;
        cout << k << endl;

        while (true) {
            string cmd;
            if (!(cin >> cmd)) finish(_pe, "Unexpected EOF from contestant");

            if (cmd == "?") {
                long long si, sj;
                if (!(cin >> si >> sj)) finish(_pe, "Malformed query");
                if (si < 1 || si > S) finish(_pe, "Query server index out of range");
                int idx = (int)si - 1;
                if (sj < 1 || sj > (long long)a[idx]) finish(_pe, "Query position out of range");

                queries++;
                if (queries > hard_cap) finish(_pe, "Hard cap exceeded");

                long long ans = ids[idx][(int)sj - 1];
                cout << ans << endl;
                log_metrics();
            } else if (cmd == "!") {
                long long ans;
                if (!(cin >> ans)) finish(_pe, "Malformed answer");
                log_metrics();
                if (ans != correct) finish(_wa, "Wrong answer");
                break;
            } else {
                finish(_pe, "Unknown command (expected '?' or '!')");
            }
        }
    }

    string extra;
    if (cin >> extra) finish(_pe, "Extra output after finishing all test cases");
    finish(_ok, "OK");
    return 0;
}

#include "testlib.h"
#include <bits/stdc++.h>
using namespace std;

static const long long LIM = 1000000000000000000LL;

static vector<int> balancedCounts(int S, int total) {
    vector<int> a(S, total / S);
    for (int i = 0; i < total % S; i++) a[i]++;
    return a;
}

static vector<vector<long long>> makeInterleavedInstance(
    int S,
    const vector<int>& a,
    long long maxInc,
    long long startHint
) {
    long long total = 0;
    for (int x : a) total += x;

    __int128 need = (__int128)total * (__int128)maxInc + 5;
    long long maxStart = (need >= LIM ? 1LL : (long long)((__int128)LIM - need));
    if (maxStart < 1) maxStart = 1;

    long long cur = (startHint >= 1 ? min(startHint, maxStart) : rnd.next(1LL, maxStart));
    vector<long long> all;
    all.reserve((size_t)total);

    for (long long i = 0; i < total; i++) {
        all.push_back(cur);
        long long inc = rnd.next(1LL, maxInc);
        __int128 nxt = (__int128)cur + (__int128)inc;
        if (nxt > LIM) nxt = LIM;
        cur = (long long)nxt;
        if (cur == LIM && i + 1 < total) {
            cur = LIM - (long long)(total - (i + 1));
        }
    }

    vector<int> perm(S);
    iota(perm.begin(), perm.end(), 0);
    for (int i = S - 1; i > 0; i--) {
        int j = rnd.next(0, i);
        swap(perm[i], perm[j]);
    }

    vector<vector<long long>> ids(S);
    for (int i = 0; i < S; i++) ids[i].reserve((size_t)a[i]);

    vector<int> used(S, 0);
    for (long long t = 0; t < total; t++) {
        int preferred = perm[(int)(t % S)];
        int s = preferred;
        if (used[s] >= a[s]) {
            s = -1;
            for (int i = 0; i < S; i++) {
                int cand = perm[i];
                if (used[cand] < a[cand]) {
                    s = cand;
                    break;
                }
            }
        }
        ids[s].push_back(all[(size_t)t]);
        used[s]++;
    }
    return ids;
}

static void printServerIdsLine(const vector<long long>& v) {
    for (int i = 0; i < (int)v.size(); i++) {
        if (i) cout << ' ';
        cout << v[i];
    }
    cout << "\n";
}

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

    string mode = opt<string>("mode", "non");
    int Sopt = opt<int>("S", 5);
    int nopt = opt<int>("n", 1);
    int maxA = opt<int>("maxA", 100000);
    long long maxInc = opt<long long>("maxInc", 1000000LL);

    long long seedValue = 0;
    if (argc >= 2) {
        seedValue = atoll(argv[1]);
        if (seedValue < 0) seedValue = -seedValue;
    }

    int S = min(max(Sopt, 1), 5);
    int n = max(nopt, 1);

    struct Case {
        vector<int> a;
        long long k;
        vector<vector<long long>> ids;
    };

    vector<Case> cases;

    auto addCaseNon = [&](int Slocal, const vector<int>& a, long long k, const vector<vector<long long>>& ids) {
        Case c;
        c.a = a;
        c.k = k;
        c.ids = ids;
        cases.push_back(std::move(c));
    };
    auto addCaseAdp = [&](const vector<int>& a, long long k) {
        Case c;
        c.a = a;
        c.k = k;
        cases.push_back(std::move(c));
    };

    if (seedValue == 1) {

        S = 1;
        n = 1;
        vector<int> a = {1};
        long long k = 1;
        if (mode == "non") {
            vector<vector<long long>> ids(1);
            ids[0] = {LIM};
            addCaseNon(S, a, k, ids);
        } else {
            addCaseAdp(a, k);
        }
    } else if (seedValue == 2) {

        S = 5;
        n = 1;
        vector<int> a = {0, 1, 0, 1, 0};
        long long k = 2;
        if (mode == "non") {
            vector<vector<long long>> ids(5);
            ids[1] = {1};
            ids[3] = {LIM};
            addCaseNon(S, a, k, ids);
        } else {
            addCaseAdp(a, k);
        }
    } else if (seedValue == 3) {

        S = 5;
        n = 3;

        {
            int total = min(maxA, 100000);
            vector<int> a = balancedCounts(S, total);
            auto ids = makeInterleavedInstance(S, a, min(maxInc, 1000LL), -1);
            long long k = total / 2 + 1;
            if (mode == "non") addCaseNon(S, a, k, ids);
            else addCaseAdp(a, k);
        }
        {
            int total = min(maxA, 100000);
            vector<int> a(S, 0);
            a[0] = total;
            auto ids = makeInterleavedInstance(S, a, min(maxInc, 1000000LL), LIM - 20000000000LL);
            long long k = (long long)total;
            if (mode == "non") addCaseNon(S, a, k, ids);
            else addCaseAdp(a, k);
        }
        {
            vector<int> a = {1, 1, 1, 1, 1};
            vector<vector<long long>> ids(5);
            ids[0] = {2};
            ids[1] = {100};
            ids[2] = {10000};
            ids[3] = {1000000};
            ids[4] = {LIM - 1};
            long long k = 4;
            if (mode == "non") addCaseNon(S, a, k, ids);
            else addCaseAdp(a, k);
        }
    } else {

        S = min(max(S, 1), 5);
        n = 1;

        int total = min(maxA, 100000);
        if (total < S) total = S;

        vector<int> a = balancedCounts(S, total);

        long long tightInc = min(maxInc, 2000LL);
        auto ids = makeInterleavedInstance(S, a, tightInc, -1);

        long long kCenter = (long long)total / 2 + 1;
        long long wiggle = rnd.next(-2LL * (long long)S, 2LL * (long long)S);
        long long k = kCenter + wiggle;
        if (k < 1) k = 1;
        if (k > total) k = total;

        if (mode == "non") addCaseNon(S, a, k, ids);
        else addCaseAdp(a, k);
    }

    n = (int)cases.size();
    cout << n << " " << S << "\n";

    for (int tc = 0; tc < n; tc++) {
        const auto& a = cases[tc].a;
        for (int i = 0; i < S; i++) {
            if (i) cout << ' ';
            cout << (i < (int)a.size() ? a[i] : 0);
        }
        cout << "\n";
        cout << cases[tc].k << "\n";

        if (mode == "non") {
            const auto& ids = cases[tc].ids;
            for (int i = 0; i < S; i++) {
                if (i < (int)ids.size()) printServerIdsLine(ids[i]);
                else cout << "\n";
            }
        }
    }

    return 0;
}


This is an interactive problem, where your program and the judge interact via standard input and output.

In the kingdom of Duloc, Lord Farquaad is developing a network of watchtowers to monitor every corner of his land. He has a map of towers and the roads that connect them, forming an undirected simple graph $G = ( V , E )$ , where each tower is a vertex and each road is an edge between two towers. However, Farquaad is worried that some parts of Duloc might be isolated, making it impossible to reach every tower from any other.

To ensure full connectivity, he tasks you with verifying whether his network is connected. However, there’s a catch: you’re only allowed limited access to information about the graph.

You can query the network to investigate its connectivity. A query allows you to select a subset of towers $S$ and receive a count of the towers not in $S$ that have direct roads connecting them to at least one tower in $S$ . More precisely, $q u e r y ( S ) = | N ( S ) \setminus S |$ , where $S \subseteq V$ and $N ( S ) = \{ x \vert \exists y \in S$ such that $( x , y ) \in E \}$ .

Your goal is to use these queries efficiently to determine if the network is connected.

Can you help Lord Farquaad confirm the security of his kingdom by verifying that every tower is reachabl from any other in Duloc’s network?

# Input

Interaction starts by reading an integer — the number of vertices.

Then you can make queries of the type "? $\mathtt { s } ^ { \mathfrak { n } }$ (without quotes) where $s$ is a binary string of length $n$ such that character $s _ { i }$ is 1 if node $i \in S$ and 0 otherwise. After the query, read an integer — the answer to your query.

After printing a query do not forget to output end of line and flush the output. The interactor is nonadaptive. The graph does not change during the interaction.

# Constraints

You are allowed to use at most 3500 queries.

# Output

When you find if $G$ is connected or disconnected, print it in the format $" ! ~ \tt ~ x "$ (without quotes), where $x$ is 1 if $G$ is connected and 0 otherwise.

# Note

In the following interaction, $| V | = 4$ , $G = ( V , E )$ , $V = \{ 1 , 2 , 3 , 4 \}$ , $E = \{ ( 1 , 2 ) , ( 2 , 3 ) , ( 3 , 4 ) , ( 2 , 4 ) \} .$ .

Input	Output	Description

4		|V| is given.

	？1100	Ask a query for subset {1,2}.

2		The judge responds with 2.

	？ 0010	Ask a query for subset {3}.

2		The judge responds with 2.

	？1001	Ask a query for subset {1,4}.

2		The judge responds with 2.

	！1	The algorithm detected that G is connected.

Here is another example, $| V | = 2$ , $G = ( V , E )$ , $V = \{ 1 , 2 \}$ , $E = \emptyset$ .

Input	Output	Description

2		|V| is given.

	？10	Ask a query for subset {1}.

0		The judge responds with 0.

	？11	Ask a query for subset {1,2}.

0		The judge responds with 0.

	！0	The algorithm detected that G is disconnected.

#include "testlib.h"
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 2048;

static bitset<MAXN> adj[MAXN];
static int N, M;

static long long queries = 0;
static long long query_limit = 3500;

void log_metrics() {
    try {
        tout << "queries=" << queries << endl;
        tout << "query_limit=" << query_limit << endl;
    } catch (...) {

    }
}

template<typename... Args>
void finish(TResult verdict, const char* fmt, Args... args) {
    log_metrics();
    quitf(verdict, fmt, args...);
}

int main(int argc, char** argv) {

    registerInteraction(argc, argv);

    atexit(log_metrics);

    N = inf.readInt();
    M = inf.readInt();

    if (N > MAXN) {
        finish(_fail, "Test case N=%d exceeds interactor capacity %d", N, MAXN);
    }

    query_limit = 3500;

    log_metrics();

    for (int i = 0; i < M; i++) {
        int u = inf.readInt();
        int v = inf.readInt();

        if (u < 1 || u > N || v < 1 || v > N) {
            finish(_fail, "Invalid edge (%d, %d) for N=%d", u, v, N);
        }

        u--; v--;

        if (u == v) continue;

        adj[u].set(v);
        adj[v].set(u);
    }

    int expected_ans = 0;
    if (N == 0) {
        expected_ans = 1;
    } else {
        int visited_count = 0;
        vector<bool> vis(N, false);
        queue<int> q;

        q.push(0);
        vis[0] = true;
        visited_count++;

        while (!q.empty()) {
            int u = q.front();
            q.pop();

            for (int v = 0; v < N; v++) {
                if (adj[u].test(v)) {
                    if (!vis[v]) {
                        vis[v] = true;
                        visited_count++;
                        q.push(v);
                    }
                }
            }
        }

        if (visited_count == N) expected_ans = 1;
        else expected_ans = 0;
    }

    cout << N << endl;

    while (true) {

        if (queries > query_limit + 500) {
            finish(_pe, "Hard query limit exceeded (potential infinite loop)");
        }

        string token;

        if (!(cin >> token)) {
            finish(_wa, "Unexpected EOF: solution finished without providing an answer");
        }

        if (token.empty()) continue;

        char type = token[0];

        if (type == '?') {
            string s;

            if (token.length() > 1) {
                s = token.substr(1);
            } else {
                if (!(cin >> s)) {
                    finish(_wa, "Unexpected EOF reading query string");
                }
            }

            if ((int)s.length() != N) {
                finish(_pe, "Invalid query string length: got %d, expected %d", (int)s.length(), N);
            }

            bitset<MAXN> mask;
            mask.reset();
            bool valid = true;
            for (int i = 0; i < N; i++) {
                if (s[i] == '1') {
                    mask.set(i);
                } else if (s[i] != '0') {
                    valid = false;
                    break;
                }
            }

            if (!valid) {
                finish(_pe, "Query string contains invalid characters (must be '0' or '1')");
            }

            bitset<MAXN> neighbors;
            neighbors.reset();

            for (int i = 0; i < N; i++) {
                if (mask.test(i)) {
                    neighbors |= adj[i];
                }
            }

            neighbors &= ~mask;

            int ans = (int)neighbors.count();

            cout << ans << endl;
            queries++;

            if (queries % 10 == 0) log_metrics();
        }
        else if (type == '!') {
            string ans_str;

            if (token.length() > 1) {
                ans_str = token.substr(1);
            } else {
                if (!(cin >> ans_str)) {
                    finish(_wa, "Unexpected EOF reading answer");
                }
            }

            int ans = -1;
            try {
                ans = stoi(ans_str);
            } catch (...) {
                finish(_pe, "Answer must be an integer");
            }

            if (ans == expected_ans) {
                finish(_ok, "Correct answer");
            } else {
                finish(_wa, "Wrong answer: expected %d, found %d", expected_ans, ans);
            }
        }
        else {
            finish(_pe, "Invalid protocol token '%s'. Expected '?' or '!'", token.c_str());
        }
    }

    return 0;
}

#include "testlib.h"
#include <bits/stdc++.h>

using namespace std;

void add_connected_edges(const vector<int>& nodes, vector<pair<int, int>>& edges, double density_factor) {
    int k = nodes.size();
    if (k <= 1) return;

    for (int i = 1; i < k; i++) {

        int parent_idx = rnd.next(i);
        int u = nodes[i];
        int v = nodes[parent_idx];
        if (u > v) swap(u, v);
        edges.push_back({u, v});
    }

    long long max_edges = (long long)k * (k - 1) / 2;
    long long current_edges = k - 1;
    long long possible_extra = max_edges - current_edges;

    if (possible_extra <= 0) return;

    long long target_extra = possible_extra * density_factor;
    long long cap = (long long)k * 5;
    if (density_factor < 0.8) {
        target_extra = min(target_extra, cap);
    }

    if (target_extra <= 0) return;

    set<pair<int, int>> existing;
    for (auto& e : edges) existing.insert(e);

    int attempts = 0;
    while (target_extra > 0 && attempts < target_extra * 5) {
        attempts++;
        int idx1 = rnd.next(k);
        int idx2 = rnd.next(k);
        if (idx1 == idx2) continue;

        int u = nodes[idx1];
        int v = nodes[idx2];
        if (u > v) swap(u, v);

        if (existing.count({u, v})) continue;

        existing.insert({u, v});
        edges.push_back({u, v});
        target_extra--;
    }
}

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

    string mode = opt<string>("mode", "non");

    int n = opt<int>("n", -1);
    long long seed_val = atoll(argv[1]);
    string type = opt<string>("t", "random");

    if (n == -1) {
        if (seed_val == 1)      { n = 2; type = "disconnected"; }
        else if (seed_val == 2) { n = 2; type = "connected"; }
        else if (seed_val == 3) { n = 5; type = "line"; }
        else if (seed_val == 4) { n = 10; type = "star"; }
        else if (seed_val == 5) { n = 50; type = "isolated_1"; }
        else if (seed_val == 6) { n = 100; type = "disconnected_half"; }
        else if (seed_val == 7) { n = 500; type = "tree"; }
        else if (seed_val == 8) { n = 500; type = "circle"; }
        else if (seed_val == 9) { n = 1000; type = "isolated_1"; }
        else if (seed_val == 10){ n = 1000; type = "bridge"; }
        else if (seed_val == 11){ n = 1000; type = "sparse_connected"; }
        else if (seed_val == 12){ n = 1000; type = "disconnected_many"; }
        else if (seed_val == 13){ n = 1000; type = "complete_ish"; }
        else if (seed_val == 14){ n = 1000; type = "random_disconnected"; }
        else {
            n = rnd.next(500, 1000);
            type = "random";
        }
    }

    if (type == "random") {
        if (rnd.next(2)) type = "connected";
        else type = "disconnected";
    }

    if (type == "connected") type = "sparse_connected";
    if (type == "disconnected") type = "random_disconnected";

    vector<int> p(n);
    iota(p.begin(), p.end(), 1);
    shuffle(p.begin(), p.end());

    vector<pair<int, int>> edges;

    if (type == "line") {
        for(int i = 0; i < n - 1; i++) {
            int u = p[i], v = p[i+1];
            if (u > v) swap(u, v);
            edges.push_back({u, v});
        }
    }
    else if (type == "circle") {
        for(int i = 0; i < n; i++) {
            int u = p[i], v = p[(i+1)%n];
            if (u > v) swap(u, v);
            edges.push_back({u, v});
        }
    }
    else if (type == "star") {
        for(int i = 1; i < n; i++) {
            int u = p[0], v = p[i];
            if (u > v) swap(u, v);
            edges.push_back({u, v});
        }
    }
    else if (type == "tree") {
        add_connected_edges(p, edges, 0.0);
    }
    else if (type == "sparse_connected") {
        add_connected_edges(p, edges, 0.05);
    }
    else if (type == "complete_ish") {
        add_connected_edges(p, edges, 1.0);
    }
    else if (type == "bridge") {

        int mid = n / 2;
        vector<int> p1(p.begin(), p.begin() + mid);
        vector<int> p2(p.begin() + mid, p.end());
        add_connected_edges(p1, edges, 0.2);
        add_connected_edges(p2, edges, 0.2);

        int u = p1[rnd.next(mid)];
        int v = p2[rnd.next(n - mid)];
        if (u > v) swap(u, v);
        edges.push_back({u, v});
    }
    else if (type == "isolated_1") {

        if (n > 1) {
            vector<int> main_comp(p.begin(), p.end() - 1);
            add_connected_edges(main_comp, edges, 0.2);

        }
    }
    else if (type == "disconnected_half") {

        int mid = n / 2;
        vector<int> p1(p.begin(), p.begin() + mid);
        vector<int> p2(p.begin() + mid, p.end());
        add_connected_edges(p1, edges, 0.2);
        add_connected_edges(p2, edges, 0.2);
    }
    else if (type == "disconnected_many") {

        int cur = 0;
        while(cur < n) {

            int sz = rnd.next(2, max(3, n/10));
            if (cur + sz > n) sz = n - cur;
            if (sz <= 1) break;

            vector<int> comp;
            for(int k=0; k<sz; k++) comp.push_back(p[cur++]);
            add_connected_edges(comp, edges, 0.5);
        }
    }
    else if (type == "random_disconnected") {

        int k = rnd.next(2, 5);
        vector<vector<int>> comps(k);
        for(int x : p) {
            comps[rnd.next(k)].push_back(x);
        }
        for(auto& comp : comps) {
            if(!comp.empty()) add_connected_edges(comp, edges, 0.2);
        }
    }
    else {

        add_connected_edges(p, edges, 0.1);
    }

    cout << n << " " << edges.size() << endl;
    for (const auto& e : edges) {
        cout << e.first << " " << e.second << "\n";
    }

    return 0;
}