This is the hard version of the problem. In this version, you must use the minimum number of queries possible.

This is an interactive problem.

It is a tradition in Mexico's national IOI trainings to play the game "Asesino", which is similar to "Among Us" or "Mafia".

Today, $n$ players, numbered from $1$ to $n$, will play "Asesino" with the following three roles:

* Knight: a Knight is someone who always tells the truth.
* Knave: a Knave is someone who always lies.
* Impostor: an Impostor is someone everybody thinks is a Knight, but is secretly a Knave.

Each player will be assigned a role in the game. There will be exactly one Impostor but there can be any (possible zero) number of Knights and Knaves.

As the game moderator, you have accidentally forgotten the roles of everyone, but you need to determine the player who is the Impostor.

To determine the Impostor, you will ask some questions. In each question, you will pick two players $i$ and $j$ ($1 \leq i, j \leq n$; $i \neq j$) and ask if player $i$ thinks that player $j$ is a Knight. The results of the question is shown in the table below.

|  |  |  |  |
| --- | --- | --- | --- |
|  | Knight | Knave | Impostor |
| Knight | Yes | No | Yes |
| Knave | No | Yes | No |
| Impostor | No | Yes | — |

The response of the cell in row $a$ and column $b$ is the result of asking a question when $i$ has role $a$ and $j$ has row $b$. For example, the "Yes" in the top right cell belongs to row "Knight" and column "Impostor", so it is the response when $i$ is a Knight and $j$ is an Impostor.

Find the Impostor in the minimum number of queries possible. That is, let $f(n)$ be the minimum integer such that for $n$ players, there exists a strategy that can determine the Impostor using at most $f(n)$ questions. Then, you should use at most $f(n)$ questions to determine the Impostor.

Note: the grader is adaptive: the roles of the players are not fixed in the beginning and may change depending on your questions. However, it is guaranteed that there exists an assignment of roles that is consistent with all previously asked questions under the constraints of this problem.

Input

The first line of input contains a single integer $t$ ($1 \leq t \leq 10^3$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($3 \le n \le 10^5$) — the number of people playing the game.

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

Interaction

To ask a question, output a line in the following format:

* "? i j" ($1 \leq i,j \leq n$; $i \neq j$) — to ask player $i$ if they think player $j$ is a Knight.

The jury will output a "1" if player $i$ thinks player $j$ is a Knight, and "0" otherwise.

When you have determined which player the Impostor is, output a line in the following format:

* "! i" ($1 \leq i \leq n$) — the Impostor is player $i$.

Note that answering does not count to your limit of $f(n)$ questions.

If you have made an invalid output, used more than $f(n)$ questions or wrongly determined the Impostor, the jury will respond with "-1" and you will receive a Wrong Answer verdict. Upon receiving "-1", your program must terminate immediately. Otherwise, you may receive an arbitrary verdict because your solution might be reading from a closed stream.

After printing a query do not forget to output the end of the 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;
* sys.stdout.flush() in Python;
* std::io::stdout().flush() in Rust;
* see the documentation for other languages.

Example

Input

```
2
7

1

0

0

1

1

0

0

4

0

1

1

1
```

Output

```
? 1 3

? 7 6

? 2 5

? 6 2

? 4 5

? 4 6

? 1 4

! 4

? 1 2

? 2 3

? 3 4

? 4 1

! 3
```

Note

Note that the example test cases do not represent an optimal strategy for asking questions and are only shown for the sake of demonstrating the interaction format. Specifically, we cannot determine which player is the Impostor from the questions asked in the examples.

In the first test case of the example, players at indices $2$ and $6$ are Knights, players at indices $1$, $3$, $5$, and $7$ are Knaves, and the Impostor is at index $4$. The following is an explanation of the questions asked:

* In the first query, player $i$ is a Knave and player $j$ is a Knave. The answer is "yes" since Knaves always lie.
* In the second query, player $i$ is a Knave and player $j$ is a Knight. The answer is "no" since Knaves always lie.
* In the third query, player $i$ is a Knight and player $j$ is a Knave. The answer is "no" since Knights always tell the truth.
* In the fourth query, player $i$ is a Knight and player $j$ is a Knight. The answer is "yes" since Knights always tell the truth.
* In the fifth query, player $i$ is a Impostor and player $j$ is a Knave. The answer is "yes" since the Impostor always lies.
* In the sixth query, player $i$ is a Impostor and player $j$ is a Knight. The answer is "no" since the Impostor always lies.
* In the seventh query, player $i$ is a Knave and player $j$ is a Impostor. The answer is "no" since Knaves always lie and Knaves thinks that the Impostor is a Knight.

#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 (...) {

    }
}

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

static void reply_minus_one_and_wa(const string& msg) {
    try {
        cout << -1 << endl;
        cout.flush();
    } catch (...) {

    }
    finish(_wa, msg);
}

static long long f_min_queries(int n) {

    if (n == 3) return 4;
    return n;
}

bool is_perceived_knight(int role) {
    return (role == 1 || role == 2);
}

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

    struct TestCase {
        int n = 0;
        vector<int> roles;
        int impostor = -1;
        long long limit = 0;
    };

    int t = inf.readInt(1, 1000, "t");
    vector<TestCase> tests;
    tests.reserve(t);

    for (int tc = 0; tc < t; tc++) {
        TestCase cur;
        cur.n = inf.readInt(3, 100000, "n");
        cur.roles.assign(cur.n + 1, 0);
        for (int i = 1; i <= cur.n; i++) {
            cur.roles[i] = inf.readInt(0, 2, "role");
            if (cur.roles[i] == 2) cur.impostor = i;
        }
        if (cur.impostor == -1) finish(_fail, "Hidden input: missing impostor");
        cur.limit = f_min_queries(cur.n);
        tests.push_back(std::move(cur));
        query_limit += tests.back().limit;
    }

    log_metrics();

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

    for (int tc = 0; tc < t; tc++) {
        const TestCase& cur = tests[tc];
        const int n = cur.n;
        const long long limit = cur.limit;

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

        long long used = 0;
        while (true) {
            if (queries > HARD_CAP) finish(_pe, "Hard query limit exceeded");

            string cmd;
            if (!(cin >> cmd)) finish(_wa, "Unexpected EOF (no answer provided)");

            if (cmd == "!") {
                int ans = 0;
                if (!(cin >> ans)) finish(_pe, "Expected impostor index after '!'");
                if (ans < 1 || ans > n) reply_minus_one_and_wa("Answer out of range");
                if (ans != cur.impostor) {
                    reply_minus_one_and_wa(format("Wrong answer: expected %d, got %d", cur.impostor, ans));
                }
                break;
            }

            if (cmd != "?") {
                reply_minus_one_and_wa("Invalid query format (expected '? i j' or '! i')");
            }

            int u = 0, v = 0;
            if (!(cin >> u >> v)) finish(_pe, "Expected two integers after '?'");
            if (u < 1 || u > n || v < 1 || v > n || u == v) {
                reply_minus_one_and_wa("Invalid query arguments");
            }

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

            if (used > limit) {
                reply_minus_one_and_wa("Query limit exceeded");
            }

            bool perceived = is_perceived_knight(cur.roles[v]);
            bool response = (cur.roles[u] == 1) ? perceived : !perceived;
            cout << (response ? 1 : 0) << endl;
            cout.flush();
        }
    }

    finish(_ok, "OK");
}

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

using namespace std;

static long long total_queries = 0;
static long long query_limit = 0;

static void log_metrics() {
    try {
        tout << "queries=" << total_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 void reply_minus_one_and_wa(const string& msg) {
    try {
        cout << -1 << endl;
        cout.flush();
    } catch (...) {

    }
    finish(_wa, msg);
}

static long long f_min_queries(int n) {

    if (n == 3) return 4;
    return n;
}

struct DSU {
    vector<int> parent;
    vector<int> diff;

    DSU(int n) {
        parent.resize(n + 1);
        iota(parent.begin(), parent.end(), 0);
        diff.assign(n + 1, 0);
    }

    pair<int, int> find(int i) {
        if (parent[i] == i) return {i, 0};
        auto root = find(parent[i]);
        parent[i] = root.first;
        diff[i] = diff[i] ^ root.second;
        return {parent[i], diff[i]};
    }

    bool unite(int i, int j, int weight) {
        auto root_i = find(i);
        auto root_j = find(j);
        if (root_i.first != root_j.first) {
            parent[root_i.first] = root_j.first;
            diff[root_i.first] = weight ^ root_i.second ^ root_j.second;
            return true;
        }
        return false;
    }

    int get_path_xor(int i, int j) {
        auto root_i = find(i);
        auto root_j = find(j);
        if (root_i.first != root_j.first) return 0;
        return root_i.second ^ root_j.second;
    }
};

struct Edge {
    int to;
    bool is_out;
};

void get_flow_through(int n, int u, int v, const vector<vector<Edge>>& adj, vector<int>& F_nodes) {
    queue<pair<int, int>> q;
    q.push({v, 0});

    vector<int> parent(n + 1, 0);

    vector<bool> edge_dir_at_child(n + 1);
    vector<bool> edge_dir_at_parent(n + 1);
    vector<bool> visited(n + 1, false);

    visited[v] = true;
    bool found = false;

    while(!q.empty()){
        auto [curr, par] = q.front(); q.pop();
        if(curr == u) { found = true; break; }
        for(auto& e : adj[curr]){
            if(e.to == par) continue;
            if(!visited[e.to]){
                visited[e.to] = true;
                parent[e.to] = curr;

                edge_dir_at_parent[e.to] = e.is_out;
                edge_dir_at_child[e.to] = !e.is_out;
                q.push({e.to, curr});
            }
        }
    }

    if (!found) return;

    vector<int> path;
    int curr = u;
    while(curr != v) {
        path.push_back(curr);
        curr = parent[curr];
    }
    path.push_back(v);

    if (!edge_dir_at_child[u]) F_nodes.push_back(u);

    if (path.size() > 1) {
        int c = path[path.size() - 2];
        if (edge_dir_at_parent[c]) F_nodes.push_back(v);
    }

    for (size_t i = 1; i < path.size() - 1; ++i) {
        int node = path[i];
        int child = path[i-1];
        if (edge_dir_at_parent[child] != edge_dir_at_child[node]) {
            F_nodes.push_back(node);
        }
    }
}

struct CaseData {
    int n;
};

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

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

    vector<CaseData> cases;
    int T = inf.readInt(1, 1000, "t");

    for (int i = 0; i < T; ++i) {
        int n = inf.readInt(3, 100000, "n");

        for (int j = 0; j < n; ++j) (void)inf.readInt();
        cases.push_back({n});
        query_limit += f_min_queries(n);
    }

    log_metrics();

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

    for (const auto& tc : cases) {
        int n = tc.n;
        const long long per_limit = f_min_queries(n);
        long long used = 0;

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

        DSU dsu(n);
        vector<vector<Edge>> tree_adj(n + 1);
        bitset<100005> candidates;
        for(int i=1; i<=n; ++i) candidates.set(i);
        int valid_count = n;

        bool solved = false;
        while (!solved) {
            string type;
            if (!(cin >> type)) finish(_wa, "Unexpected EOF");

            if (type == "!") {
                int ans;
                if (!(cin >> ans)) finish(_wa, "Unexpected EOF after !");

                if (ans < 1 || ans > n) reply_minus_one_and_wa("Answer out of range");

                if (!candidates.test(ans)) {
                    reply_minus_one_and_wa("Incorrect impostor identified");
                }

                if (valid_count > 1) {
                    reply_minus_one_and_wa("Ambiguous answer: multiple candidates remain valid");
                }

                solved = true;

            } else {

                int u, v;
                if (type != "?") {
                    reply_minus_one_and_wa("Invalid query format (expected '? i j')");
                }
                if (!(cin >> u >> v)) finish(_wa, "Unexpected EOF reading query args");

                total_queries++;

                if (total_queries % 1000 == 0) log_metrics();

                used++;
                if (used > per_limit) {
                    reply_minus_one_and_wa("Query limit exceeded");
                }

                if (u < 1 || u > n || v < 1 || v > n || u == v) {
                    reply_minus_one_and_wa("Invalid query arguments");
                }

                if (dsu.find(u).first != dsu.find(v).first) {

                    int ans = 0;
                    dsu.unite(u, v, ans ^ 1);

                    tree_adj[u].push_back({v, true});
                    tree_adj[v].push_back({u, false});

                    cout << ans << endl;
                } else {

                    int path_xor = dsu.get_path_xor(u, v);
                    int ans_normal = path_xor ^ 1;
                    int ans_conflict = 1 - ans_normal;

                    vector<int> F_nodes;
                    get_flow_through(n, u, v, tree_adj, F_nodes);

                    int valid_in_F = 0;
                    for (int x : F_nodes) {
                        if (candidates.test(x)) valid_in_F++;
                    }

                    int size_A = valid_count - valid_in_F;
                    int size_B = valid_in_F;

                    if (size_A >= size_B) {

                        for (int x : F_nodes) {
                            if (candidates.test(x)) {
                                candidates.reset(x);
                                valid_count--;
                            }
                        }
                        cout << ans_normal << endl;
                    } else {

                        vector<int> survivors;
                        for(int x : F_nodes) {
                            if(candidates.test(x)) survivors.push_back(x);
                        }
                        candidates.reset();
                        for(int x : survivors) candidates.set(x);
                        valid_count = survivors.size();
                        cout << ans_conflict << endl;
                    }
                }
                cout.flush();
            }
        }
    }

    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");
    int n = opt<int>("n", -1);

    if (n == -1) {
        int p = rnd.next(100);
        if (p < 5) n = 3;
        else if (p < 10) n = rnd.next(4, 10);
        else if (p < 20) n = rnd.next(11, 100);
        else if (p < 35) n = rnd.next(101, 2000);
        else if (p < 95) n = rnd.next(2001, 100000);
        else n = 100000;
    }

    println(1);

    println(n);

    if (mode == "adp") {

        vector<int> a(n, -1);
        println(a);
    } else {

        vector<int> a(n);
        int impostor_idx = rnd.next(n);

        int type = rnd.next(5);

        for (int i = 0; i < n; i++) {
            if (i == impostor_idx) {
                a[i] = 2;
            } else {
                int role = 0;
                if (type == 0) role = 1;
                else if (type == 1) role = 0;
                else if (type == 2) role = (rnd.next(10) == 0 ? 0 : 1);
                else if (type == 3) role = (rnd.next(10) == 0 ? 1 : 0);
                else role = rnd.next(0, 1);
                a[i] = role;
            }
        }
        println(a);
    }

    return 0;
}


# This is an interactive problem.

A mischievous robot is navigating an infinitely large 2D grid. However, its movement is confined to the first quadrant, meaning its coordinates $( x , y )$ must always satisfy $x > 0$ and $y > 0$ . Initially, the robot is located at grid coordinates $( s _ { x } , s _ { y } )$ . All grid cells are initially white.

The game proceeds in discrete time steps, up to a maximum of $T = 1 0 0 0$ steps. In each time step, the following sequence occurs:

1. Your Move: You choose integer coordinates $( x _ { m } , y _ { m } )$ such that $1 \leq x _ { m } \leq T$ and $1 \leq y _ { m } \leq T$ . You then mark this cell black. A cell, once marked black, remains black for the rest of the game. You can mark any cell within the range, including the cell where the robot is currently located.

2. Robot’s Move: The robot, currently at position $( r _ { x } , r _ { y } )$ , observes the grid (including the cell you just marked black). It knows the locations of all currently black cells. It then moves to a new position $( n _ { x } , n _ { y } )$ . The new position $( n _ { x } , n _ { y } )$ must be one of the 8 cells immediately adjacent (horizontally, vertically, or diagonally) to $( r _ { x } , r _ { y } )$ . That is, $| n _ { x } - r _ { x } | \le 1$ and $| n _ { y } - r _ { y } | \le 1$ , and $( n _ { x } , n _ { y } ) \neq ( r _ { x } , r _ { y } )$ . Additionally, the robot must stay within the first quadrant, so $n _ { x } > 0$ and $n _ { y } > 0$ . The interactor (controlling the robot) will choose one valid move for the robot. The robot’s strategy is unknown to you.

3. Outcome Check: After the robot moves to $( n _ { x } , n _ { y } )$ , the system checks if the cell $( n _ { x } , n _ { y } )$ is black.

• If $( n _ { x } , n _ { y } )$ is black, the robot explodes.
• If $( n _ { x } , n _ { y } )$ is white, the game continues to the next time step, with the robot now at $( n _ { x } , n _ { y } )$ .

Your goal is to make the robot explode within $T$ time steps.

# Input

The first line of input contains two integers $s _ { x }$ and $s _ { y }$ ( $1 \leq s _ { x } , s _ { y } \leq 2 0 _ { , }$ ), the initial coordinates of the robot.

# Interaction Protocol

The interaction proceeds in turns for at most $T$ turns. In each turn $t$ (from $t = 1$ to $T$ ):

1. Your program must print one line containing two space-separated integers $x _ { m }$ and $y _ { m }$ , representing the coordinates of the cell you choose to mark black in this turn. Remember to flush the output stream.

2. The interactor reads your chosen coordinates $\left( x _ { m } , y _ { m } \right)$ .

3. The interactor determines the robot’s next move to $( n _ { x } , n _ { y } )$ based on its current position and the set of all black cells (including the one just marked at $( x _ { m } , y _ { m } ) )$ .

4. The interactor checks if the cell $( n _ { x } , n _ { y } )$ is black.

• If it is black (robot explodes), the interactor will print a single line containing $" 0 \ 0 ^ { \prime }$ and terminate. Your program should then read these values and terminate successfully.

• If it is white, the interactor will print a single line containing two space-separated integers $n _ { x }$ and $n _ { y }$ , the new coordinates of the robot. Your program should read these coordinates to know the robot’s current position for the next turn.

If the robot has not exploded after you have made $T$ moves, your program should terminate. Your solution will be judged as incorrect in this case (or if you exceed the turn limit or make an invalid move).

To flush your output, you can use:

• fflush(stdout) (if you use printf) or cout.flush() (if you use cout) in C and C++.
• System.out.flush() in Java.
• stdout.flush() in Python.

Note: If your program does not terminate properly, it may be judged as a Presentation Error (PE).

# Example

standard input	 standard output

55	61

54

53	41

52	62

	42

51

00	52

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

using namespace std;

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

static int rx, ry;
static set<pair<int, int>> black_cells;
static bool adaptive_mode = false;
static unsigned long long rng_state = 88172645463325252ULL;

unsigned long long next_rng() {
    rng_state ^= (rng_state << 13);
    rng_state ^= (rng_state >> 7);
    rng_state ^= (rng_state << 17);
    return rng_state;
}

long long dist_sq(int x1, int y1, int x2, int y2) {
    long long dx = x1 - x2;
    long long dy = y1 - y2;
    return dx*dx + dy*dy;
}

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

    }
}

static void cleanup() {
    log_metrics();
}

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

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

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

    rx = inf.readInt(1, 20, "sx");
    ry = inf.readInt(1, 20, "sy");
    int mode_val = inf.readInt(0, 1, "is_adaptive");
    adaptive_mode = (mode_val == 1);

    log_metrics();
    cout << rx << " " << ry << endl;

    while (queries < query_limit) {

        string s1;
        if (!(cin >> s1)) {
            finish(_wa, "Unexpected EOF (contestant terminated early)");
        }

        string sx, sy;

        if (s1 == "!") {
             finish(_wa, "Contestant output '!', expected coordinates");
        } else if (s1 == "?") {
            if (!(cin >> sx >> sy)) finish(_wa, "EOF after '?'");
        } else {
            sx = s1;
            if (!(cin >> sy)) finish(_wa, "EOF after x coordinate");
        }

        int mx, my;
        try {
            mx = stoi(sx);
            my = stoi(sy);
        } catch (...) {
            finish(_wa, "Invalid integer format in coordinates");
        }

        if (mx < 1 || mx > 1000 || my < 1 || my > 1000) {
            finish(_wa, format("Coordinate out of bounds: %d %d", mx, my));
        }

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

        black_cells.insert({mx, my});

        vector<pair<int,int>> valid;
        for(int dx=-1; dx<=1; ++dx){
            for(int dy=-1; dy<=1; ++dy){
                if(!dx && !dy) continue;
                int nx = rx + dx;
                int ny = ry + dy;
                if(nx > 0 && ny > 0) valid.push_back({nx, ny});
            }
        }

        if(valid.empty()) {
            finish(_fail, "Robot stuck (no valid geometric neighbors)");
        }

        vector<pair<int,int>> safe, unsafe;
        for(auto p : valid) {
            if(black_cells.count(p)) unsafe.push_back(p);
            else safe.push_back(p);
        }

        pair<int,int> choice = {-1, -1};

        if (safe.empty()) {

            choice = unsafe[0];
        } else {
            if (!adaptive_mode) {

                int idx = next_rng() % safe.size();
                choice = safe[idx];
            } else {

                long long best_val = -1;
                vector<pair<int,int>> best_opts;

                for(auto p : safe) {
                    long long min_d = -1;
                    for(auto b : black_cells) {
                        long long d = dist_sq(p.first, p.second, b.first, b.second);
                        if(min_d == -1 || d < min_d) min_d = d;
                    }
                    if(min_d > best_val) {
                        best_val = min_d;
                        best_opts.clear();
                        best_opts.push_back(p);
                    } else if(min_d == best_val) {
                        best_opts.push_back(p);
                    }
                }

                long long best_tie = -1;
                pair<int,int> winner = {-1, -1};

                for(auto p : best_opts) {
                    long long d_last = dist_sq(p.first, p.second, mx, my);
                    if(d_last > best_tie) {
                        best_tie = d_last;
                        winner = p;
                    } else if (d_last == best_tie) {
                        if(p.first + p.second > winner.first + winner.second) {
                            winner = p;
                        } else if (p.first + p.second == winner.first + winner.second) {
                            if (p.first > winner.first) winner = p;
                        }
                    }
                }
                choice = winner;
            }
        }

        bool dead = black_cells.count(choice);
        if(dead) {
            cout << "0 0" << endl;
            finish(_ok, "Robot exploded");
        } else {
            rx = choice.first;
            ry = choice.second;
            cout << rx << " " << ry << endl;
        }
    }

    finish(_wa, "Turn limit exceeded (robot survived)");
}

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

using namespace std;

static int queries = 0;
static const int query_limit = 1000;
static const int MAX_COORD = 1000;

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 Point {
    int x, y;
    bool operator<(const Point& other) const {
        if (x != other.x) return x < other.x;
        return y < other.y;
    }
    bool operator==(const Point& other) const {
        return x == other.x && y == other.y;
    }
};

set<Point> black_cells;
Point robot_pos;

long long dist_sq(Point a, Point b) {
    long long dx = a.x - b.x;
    long long dy = a.y - b.y;
    return dx * dx + dy * dy;
}

long long get_nearest_black_dist(Point p) {
    if (black_cells.empty()) return 4000000000000000000LL;
    long long min_d = 4000000000000000000LL;
    for (const auto& b : black_cells) {
        min_d = min(min_d, dist_sq(p, b));
    }
    return min_d;
}

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

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

    int sx = inf.readInt();
    int sy = inf.readInt();

    if (!inf.seekEof()) {
        inf.readInt();
    }

    robot_pos = {sx, sy};
    queries = 0;

    log_metrics();

    cout << sx << " " << sy << endl;

    for (int t = 1; t <= query_limit; t++) {

        int xm, ym;
        if (!(cin >> xm >> ym)) {
            finish(_pe, "Failed to read user move (EOF or invalid format)");
        }

        queries = t;

        log_metrics();

        if (xm < 1 || xm > MAX_COORD || ym < 1 || ym > MAX_COORD) {
            finish(_pe, format("Invalid coordinates %d %d (must be 1..%d)", xm, ym, MAX_COORD));
        }

        black_cells.insert({xm, ym});

        vector<Point> candidates;
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                if (dx == 0 && dy == 0) continue;
                int nx = robot_pos.x + dx;
                int ny = robot_pos.y + dy;
                if (nx > 0 && ny > 0) {
                    candidates.push_back({nx, ny});
                }
            }
        }

        vector<Point> white, black;
        for (const auto& p : candidates) {
            if (black_cells.count(p)) black.push_back(p);
            else white.push_back(p);
        }

        bool exploded = false;
        Point next_p = {0, 0};

        if (white.empty()) {

            if (!black.empty()) {
                next_p = black[0];
                exploded = true;
            } else {

                finish(_pe, "Robot has no valid moves");
            }
        } else {

            Point best_p = white[0];
            long long best_d = get_nearest_black_dist(best_p);
            long long best_s = (long long)best_p.x + best_p.y;

            for (size_t i = 1; i < white.size(); i++) {
                Point p = white[i];
                long long d = get_nearest_black_dist(p);
                long long s = (long long)p.x + p.y;

                bool better = false;
                if (d > best_d) {
                    better = true;
                } else if (d == best_d) {
                    if (s > best_s) {
                        better = true;
                    } else if (s == best_s) {

                        if (p.x < best_p.x || (p.x == best_p.x && p.y < best_p.y)) {
                            better = true;
                        }
                    }
                }

                if (better) {
                    best_p = p;
                    best_d = d;
                    best_s = s;
                }
            }
            next_p = best_p;
        }

        if (exploded) {
            cout << "0 0" << endl;
            finish(_ok, format("Robot exploded at step %d", t));
        } else {
            cout << next_p.x << " " << next_p.y << endl;
            robot_pos = next_p;
        }
    }

    finish(_wa, "Robot survived T steps");

    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");
    int is_adaptive = (mode == "adp" ? 1 : 0);

    long long seed_val = 0;
    string s_arg = argv[1];
    if (!s_arg.empty() && all_of(s_arg.begin(), s_arg.end(), ::isdigit) && s_arg.size() < 18) {
        seed_val = atoll(s_arg.c_str());
    }

    int sx, sy;

    if (seed_val == 1) {
        sx = 1; sy = 1;
    } else if (seed_val == 2) {
        sx = 20; sy = 20;
    } else if (seed_val == 3) {
        sx = 1; sy = 20;
    } else if (seed_val == 4) {
        sx = 20; sy = 1;
    } else if (seed_val == 5) {
        sx = 10; sy = 10;
    } else {

        sx = rnd.next(1, 20);
        sy = rnd.next(1, 20);
    }

    cout << sx << " " << sy << endl;
    cout << is_adaptive << endl;

    return 0;
}


This is an interactive problem.

Grammy has an undirected cyclic graph of $n$ ( $4 \leq n \leq 1 0 ^ { 9 }$ ) vertices numbered from 1 to $n$ . An undirected cyclic graph is a graph of $n$ vertices and $n$ undirected edges that form one cycle. Specifically, there is a bidirectional edge between vertex $i$ and vertex $( ( i \mathrm { ~ m o d ~ } n ) + 1 \quad$ ) for each $1 \leq i \leq n$ .

Grammy thinks that this graph is too boring, so she secretly chooses a pair of non-adjacent vertices and connects an undirected edge (called a chord) between them, so that the graph now contains $n$ vertices and $( n + 1 )$ edges.

Your task is to guess the position of the chord by making no more than 40 queries. Each query consists of two vertices $x$ and $y$ , and Grammy will tell you the number of edges on the shortest path between the two vertices.

Note that the interactor is non-adaptive, meaning that the position of the chord is pre-determined.

# Input

There are multiple test cases. The first line of the input contains an integer $T$ ( $1 \le T \le 1 0 ^ { 3 }$ ) indicating the number of test cases. For each test case:

The first line contains an integer $n$ ( $4 \leq n \leq 1 0 ^ { 9 }$ ) indicating the number of vertices.

# Interaction Protocol

To ask a query, output one line. First output ? followed by a space, then output two vertices $x$ and $y$ $( 1 \leq x , y \leq n )$ separated by a space. After flushing your output, your program should read a single integer indicating the number of edges on the shortest path between the two vertices.

To guess the position of the chord, output one line. First output ! followed by a space, then output two vertices $u$ and $v$ ( $1 \leq u , v \leq n$ ) separated by a space, indicating that the chord connects vertices $u$ and $v$ . After flushing your output, your program should read a single integer $r$ $\mathrm { ~ \chi ~ } r \in \{ 1 , - 1 \}$ ) indicating the correctness of your guess. If $r = 1$ then your guess is correct, and your program should continue processing the next test case, or exit immediately if there are no more test cases. Otherwise if $r = - 1$ then your guess is incorrect, and your program should exit immediately to receive a Wrong Answer verdict. Note that your guess does not count as a query.

To flush your output, you may use:

• fflush(stdout) (if you use printf) or cout.flush() (if you use cout) in C and $\mathrm { C } + +$ .
• System.out.flush() in Java.
• stdout.flush() in Python.

# Example

standard input	standard output

2

	？15

2	？24

1

1	！42

4

2	？24

1	！13

# Note

The graphs in the sample test cases are illustrated as follows:

![](images/0dd972cad3acff0afcab244567ee31223dec8aded4f8fac1463d66d274b098ae.jpg)

#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 = 500000;

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());
}

long long dist_cycle(long long n, long long a, long long b) {
    if (a == b) return 0;
    long long d = abs(a - b);
    return min(d, n - d);
}

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

    registerInteraction(argc, argv);

    atexit(log_metrics);

    int t_cases = inf.readInt();

    query_limit = (long long)t_cases * 40;

    log_metrics();

    cout << t_cases << endl;

    for (int t = 1; t <= t_cases; ++t) {

        long long n = inf.readLong();
        long long u = inf.readLong();
        long long v = inf.readLong();

        cout << n << endl;

        bool solved = false;
        while (true) {

            string token;
            if (!(cin >> token)) {
                finish(_wa, "Unexpected EOF (contestant output ended prematurely)");
            }

            if (token == "!") {
                long long gu, gv;
                if (!(cin >> gu >> gv)) {
                    finish(_wa, "Unexpected EOF reading answer coordinates");
                }

                if (gu < 1 || gu > n || gv < 1 || gv > n) {
                    finish(_wa, "Guessed vertices out of range [1, n]");
                }

                bool correct = false;
                if ((gu == u && gv == v) || (gu == v && gv == u)) {
                    correct = true;
                }

                if (correct) {
                    cout << 1 << endl;
                    solved = true;
                    break;
                } else {
                    cout << -1 << endl;
                    finish(_wa, "Incorrect guess");
                }
            }

            else {
                long long qx, qy;

                if (token == "?") {
                    if (!(cin >> qx >> qy)) {
                        finish(_wa, "Unexpected EOF reading query coordinates");
                    }
                } else {

                    try {
                        qx = stoll(token);
                    } catch (...) {
                        finish(_wa, "Invalid token in output (expected integer, '?' or '!')");
                    }
                    if (!(cin >> qy)) {
                        finish(_wa, "Unexpected EOF reading query y coordinate");
                    }
                }

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

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

                if (qx < 1 || qx > n || qy < 1 || qy > n) {
                    finish(_wa, "Query vertices out of range [1, n]");
                }

                long long d_orig = dist_cycle(n, qx, qy);
                long long d_via_uv = dist_cycle(n, qx, u) + 1 + dist_cycle(n, v, qy);
                long long d_via_vu = dist_cycle(n, qx, v) + 1 + dist_cycle(n, u, qy);

                long long ans = min({d_orig, d_via_uv, d_via_vu});

                cout << ans << endl;
            }
        }

        if (!solved) {
            finish(_wa, "Logic error: loop terminated without solution");
        }
    }

    finish(_ok, "All test cases passed");
    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");

    long long input_n = opt<long long>("n", 0);

    int input_t = opt<int>("t", 10);

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

    vector<long long> cases_n;

    if (input_n > 0) {

        for (int i = 0; i < input_t; ++i) cases_n.push_back(input_n);
    } else if (seed == 1) {

        cases_n = {4, 4, 5, 5, 6, 6, 7, 7, 8, 8};
    } else if (seed == 2) {

        long long M = 1000000000;
        cases_n = {M, M, M-1, M-1, M-2, M/2, M/2+1, 999999999, 1000000000, 1000000000};
    } else if (seed == 3) {

        cases_n = {16, 32, 64, 128, 256, 1024, 65536, 1000000, 500000000, 1000000000};
    } else {

        for (int i = 0; i < input_t; ++i) {
            int p = rnd.next(100);
            long long n;

            if (p < 5) n = rnd.next(4, 10);
            else if (p < 20) n = rnd.next(11, 1000);
            else if (p < 50) n = rnd.next(1001, 1000000);
            else if (p < 80) n = rnd.next(1000001, 1000000000);
            else n = rnd.next(4, 1000000000);
            cases_n.push_back(n);
        }
    }

    cout << cases_n.size() << endl;

    for (long long n : cases_n) {
        if (mode == "non") {

            long long k;
            int type = rnd.next(10);
            if (type < 2) k = 2;
            else if (type < 4) k = n / 2;
            else k = rnd.next(2LL, n - 2);

            if (k < 2) k = 2;
            if (k > n - 2) k = n - 2;

            long long u = rnd.next(1LL, n);

            long long v = (u + k - 1) % n + 1;

            if (rnd.next(2)) swap(u, v);

            cout << n << " " << u << " " << v << endl;
        } else {

            cout << n << endl;
        }
    }

    return 0;
}


This is an interactive problem.

There is a secret sequence $a_1, a_2, \ldots, a_{2n-1},a_{2n}$, which contains each integer from $1$ to $n$ exactly twice.

Your task is to guess the sequence by using queries of the following type:

* "? $k\;j_1\;j_2\;\ldots\;j_k$" — select the integer $k$ ($1 \le k \le 2n$) and $k$ distinct indices $j_1, j_2, \ldots, j_k$ ($1 \le j_1 , j_2 , \ldots , j_k \le 2n$). In response to the query, the jury will return $\text{MAD}([a_{j_1}, a_{j_2}, \ldots, a_{j_k}])$.

We define the $\operatorname{MAD}$ (Maximum Appearing Duplicate) of an integer sequence as the largest integer that appears at least twice. Specifically, if there is no number that appears at least twice, the $\operatorname{MAD}$ value is $0$. Some examples are as follows:

* $\operatorname{MAD}([1, 2, 1]) = 1$;
* $\operatorname{MAD}([2, 2, 3, 3]) = 3$;
* $\operatorname{MAD}([1, 2, 3, 4]) = 0$.

Please identify the secret sequence using at most $3n$ queries.

Input

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

The first line of each test case contains one integer $n$ ($2 \le n \le 300$).

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

After you read this line of input, the interaction begins with your first query.

Interaction

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

* "? $k\;j_1\;j_2\;\ldots\;j_k$" ($1 \le k \le 2n$, $1 \le j_1 , j_2 , \ldots , j_k \le 2n$)

Here, the indices $j_1 , j_2 , \ldots , j_k$ which you selected must be pairwise distinct.

Then, after each query, read a single integer — the answer to your query.

You can make at most $3n$ queries of this type.

If your program has found the sequence $a$, print the line (without quotes) in the following format:

* "! $a_1\;a_2\;\ldots\;a_{2n-1}\;a_{2n}$" ($1 \le a_i \le n$)

Note that this does not count towards the query limit.

After this, proceed to the next test case, or exit if this is the last test case.

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

If you make more than $3n$ queries 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 each line, do not forget to output the end of line and flush the output buffer. Otherwise, you will receive the Idleness Limit Exceeded verdict. To flush, use:

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

Example

Input

```
2
2

2

0

1

2

0

1

1
```

Output

```
? 2 2 1

? 2 1 3

? 3 1 3 4

! 2 2 1 1

? 2 1 2

? 2 1 3

? 3 1 3 4

! 1 2 1 2
```

Note

In the first test case, the hidden sequence is $a=[2,2,1,1]$.

For the query "? 2 2 1", the jury returns $2$ because $\operatorname{MAD}([a_2, a_1]) = \operatorname{MAD}([2, 2]) = 2$.

For the query "? 2 1 3", the jury returns $0$ because $\operatorname{MAD}([a_1, a_3]) = \operatorname{MAD}([2, 1]) = 0$.

For the query "? 3 1 3 4", the jury returns $1$ because $\operatorname{MAD}([a_1, a_3, a_4]) = \operatorname{MAD}([2 ,1, 1]) = 1$.

Note that the example interaction is only for understanding statements and does not guarantee finding a unique sequence $a$.

#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 readLongLongFromCin(long long& x) {
    if (!(cin >> x)) return false;
    return true;
}

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

    try {
        int t = inf.readInt(1, 3000, "t");

        struct TestCase {
            int n;
            vector<int> a;
        };

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

        long long totalLimit = 0;
        for (int tc = 0; tc < t; ++tc) {
            int n = inf.readInt(2, 300, "n");
            vector<int> a(2 * n);
            for (int i = 0; i < 2 * n; ++i) {
                a[i] = inf.readInt(1, n, "a[i]");
            }
            tests.push_back(TestCase{n, std::move(a)});
            totalLimit += 3LL * n;
        }

        query_limit = totalLimit;
        log_metrics();

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

        cout << t << '\n';
        cout.flush();
        for (int tc = 0; tc < t; ++tc) {
            cout << tests[tc].n << '\n';
            cout.flush();
        }

        for (int tc = 0; tc < t; ++tc) {
            const int n = tests[tc].n;
            const vector<int>& a = tests[tc].a;
            const int m = 2 * n;

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

                if (kind == "?") {
                    long long kll;
                    if (!readLongLongFromCin(kll)) finish(_pe, "Malformed query: missing k");
                    if (kll < 1 || kll > m) finish(_pe, "Query k out of range");
                    int k = (int)kll;

                    vector<int> idx;
                    idx.reserve(k);
                    vector<char> seen(m + 1, 0);
                    for (int i = 0; i < k; ++i) {
                        long long jll;
                        if (!readLongLongFromCin(jll)) finish(_pe, "Malformed query: missing index");
                        if (jll < 1 || jll > m) finish(_pe, "Query index out of range");
                        int j = (int)jll;
                        if (seen[j]) finish(_pe, "Query indices are not distinct");
                        seen[j] = 1;
                        idx.push_back(j);
                    }

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

                    vector<int> freq(n + 1, 0);
                    int mad = 0;
                    for (int j : idx) {
                        int v = a[j - 1];
                        int c = ++freq[v];
                        if (c == 2) mad = max(mad, v);
                    }

                    cout << mad << '\n';
                    cout.flush();
                } else if (kind == "!") {
                    vector<int> ans(m);
                    vector<int> freq(n + 1, 0);

                    for (int i = 0; i < m; ++i) {
                        long long xll;
                        if (!readLongLongFromCin(xll)) finish(_pe, "Malformed answer: not enough numbers");
                        if (xll < 1 || xll > n) finish(_wa, "Answer value out of range");
                        ans[i] = (int)xll;
                        freq[ans[i]]++;
                    }

                    for (int v = 1; v <= n; ++v) {
                        if (freq[v] != 2) finish(_wa, "Answer does not contain each number exactly twice");
                    }

                    if (ans != a) finish(_wa, "Answer sequence is incorrect");

                    break;
                } else {
                    finish(_pe, "Unexpected token (expected '?' or '!')");
                }
            }
        }

        finish(_ok, "OK");
    } catch (const std::exception& e) {
        finish(_pe, string("Exception: ") + e.what());
    } catch (...) {
        finish(_pe, "Unknown exception");
    }
}

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

static vector<int> randPerm(int n) {
    vector<int> p(n);
    iota(p.begin(), p.end(), 1);
    for (int i = n - 1; i >= 1; --i) {
        int j = rnd.next(0, i);
        swap(p[i], p[j]);
    }
    return p;
}

static vector<int> derangedFrom(const vector<int>& p) {
    int n = (int)p.size();
    vector<int> q = p;
    for (int i = n - 1; i >= 1; --i) {
        int j = rnd.next(0, i);
        swap(q[i], q[j]);
    }
    if (n == 2) {
        if (q[0] == p[0] && q[1] == p[1]) swap(q[0], q[1]);
        return q;
    }
    for (int pass = 0; pass < 5; ++pass) {
        bool ok = true;
        for (int i = 0; i < n; ++i) {
            if (q[i] == p[i]) {
                ok = false;
                int j = (i + 1) % n;
                swap(q[i], q[j]);
            }
        }
        if (ok) break;
    }
    for (int i = 0; i < n; ++i) {
        if (q[i] == p[i]) {
            int j = (i + 1) % n;
            swap(q[i], q[j]);
        }
    }
    return q;
}

static vector<int> buildSequence(int n, const string& layout, long long seed) {
    vector<int> a;
    a.reserve(2 * n);

    if (seed == 1) {
        n = 2;
        return vector<int>{1, 2, 1, 2};
    }
    if (seed == 2) {
        n = 3;
        return vector<int>{1, 2, 3, 1, 3, 2};
    }
    if (seed == 3) {
        n = 300;
        for (int i = 1; i <= n; ++i) a.push_back(i);
        for (int i = n; i >= 1; --i) a.push_back(i);
        return a;
    }

    string L = layout;
    if (L == "auto") {
        int pick = rnd.next(0, 2);
        L = (pick == 0 ? "block" : (pick == 1 ? "interleave" : "mirrorblock"));
    }

    if (L == "paired") {
        for (int x = 1; x <= n; ++x) {
            a.push_back(x);
            a.push_back(x);
        }
        return a;
    }

    if (L == "mirror") {
        for (int i = 1; i <= n; ++i) a.push_back(i);
        for (int i = n; i >= 1; --i) a.push_back(i);
        return a;
    }

    vector<int> p = randPerm(n);
    vector<int> q = derangedFrom(p);

    if (L == "mirrorblock") {
        a.insert(a.end(), p.begin(), p.end());
        for (int i = n - 1; i >= 0; --i) a.push_back(p[i]);
        return a;
    }

    if (L == "block") {
        a.insert(a.end(), p.begin(), p.end());
        a.insert(a.end(), q.begin(), q.end());
        return a;
    }

    if (L == "interleave") {
        for (int i = 0; i < n; ++i) {
            a.push_back(p[i]);
            a.push_back(q[i]);
        }
        return a;
    }

    a.insert(a.end(), p.begin(), p.end());
    a.insert(a.end(), q.begin(), q.end());
    return a;
}

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

    string mode = opt<string>("mode", "non");
    int nOpt = opt<int>("n", 300);
    string layout = opt<string>("layout", "auto");

    long long seed = 0;
    if (argc >= 2) seed = atoll(argv[1]);

    int n = nOpt;
    if (seed == 1) n = 2;
    if (seed == 2) n = 3;
    if (seed == 3) n = 300;
    n = max(2, min(300, n));

    cout << 1 << "\n";

    if (mode == "adp") {
        cout << n << "\n";
        return 0;
    }

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

    vector<int> a = buildSequence(n, layout, seed);
    if ((int)a.size() != 2 * n) {
        vector<int> fallback;
        fallback.reserve(2 * n);
        for (int i = 1; i <= n; ++i) fallback.push_back(i);
        for (int i = 1; i <= n; ++i) fallback.push_back(i);
        a.swap(fallback);
    }

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


This is the hard version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 57 queries.

This is an interactive problem!

salyg1n has given you a positive integer $k$ and wants to play a game with you. He has chosen an array of $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$). You must print $a_1 \oplus a_2 \oplus \ldots \oplus a_n$, where $\oplus$ denotes the bitwise XOR operation. You can make queries of the following type:

* $?$ $i$: in response to this query, you will receive $a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}$. Also, after this query, the subarray $a_i, a_{i + 1}, \ldots, a_{i + k - 1}$ will be reversed, i.e., the chosen array $a$ will become: $a_1, a_2, \ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \ldots, a_{i + 1}, a_i, a_{i + k}, \ldots, a_n$.

You can make no more than $57$ queries to answer the problem.

Input

The first line contains a single integer $t$ ($1 \leq t \leq 1000$) – the number of test cases.

Interaction

The interaction between your program and the jury's program begins with reading two positive even integers $n$ and $k$ ($1 \leq k \leq n \leq k^2 \leq 2500$) – the length of the chosen array and the length of the query subarray, respectively.

To find the value of $a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}$, print the query in the format $?$ $i$ ($1 \leq i \leq n - k + 1$). Then read a single integer – the answer to your query.

You can make no more than $57$ queries. When you are ready to print the answer, output it in the format $!$ $x$. 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 one of the $57$ queries.

If your program makes more than $57$ queries for one set of input data, or makes an invalid query, then the response to the query will be -1. After receiving such a response, your program should immediately terminate to receive the verdict Wrong Answer. Otherwise, it may receive any other verdict.

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.

It is guaranteed that the sum of $n$ over all test cases does not exceed $10000$. The interactor in this problem is not adaptive.

Example

Input

```
2
4 2

6

4

6 6

4
```

Output

```? 1? 3! 2? 1! 4
```

Note

In the first test case, the jury has chosen the array $a$ $=$ $[4, 2, 5, 1]$

In the second test case, the jury has chosen the array $a$ $=$ $[5, 7, 1, 3, 3, 7]$

#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());
}

static bool read_token(string& tok) {
    if (!(cin >> tok)) return false;
    return true;
}

static void respond_invalid_query(const string& reason) {
    cout << -1 << endl;
    cout.flush();
    finish(_wa, reason);
}

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

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

    int t = inf.readInt(1, 1000, "t");
    cout << t << endl;
    cout.flush();

    for (int tc = 0; tc < t; ++tc) {
        int n = inf.readInt(1, 2500, "n");
        int k = inf.readInt(1, n, "k");

        vector<long long> a(n);
        long long expected = 0;
        for (int i = 0; i < n; ++i) {
            a[i] = inf.readLong(1, 1000000000LL, "a_i");
            expected ^= a[i];
        }

        cout << n << " " << k << endl;
        cout.flush();

        int q = 0;
        const int QLIM = 57;
        query_limit += QLIM;
        log_metrics();

        while (true) {
            string tok;
            if (!read_token(tok)) {
                finish(_wa, "Unexpected EOF from contestant");
            }

            if (tok == "?") {
                int i = 0;
                if (!(cin >> i)) {
                    respond_invalid_query("Bad query format");
                }
                if (q >= QLIM) {
                    respond_invalid_query("Too many queries");
                }
                if (i < 1 || i > n - k + 1) {
                    respond_invalid_query("Query index out of range");
                }

                long long x = 0;
                for (int j = 0; j < k; ++j) x ^= a[(i - 1) + j];
                reverse(a.begin() + (i - 1), a.begin() + (i - 1) + k);

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

                q++;
                queries++;
                if (queries % 200 == 0) log_metrics();
                continue;
            }

            if (!tok.empty() && tok[0] == '?') respond_invalid_query("Bad query format");

            if (tok == "!") {
                long long ans = 0;
                if (!(cin >> ans)) {
                    finish(_wa, "Bad answer format");
                }
                if (ans != expected) {
                    finish(_wa, format("Wrong answer: expected %lld, got %lld", expected, ans));
                }
                break;
            }

            if (!tok.empty() && tok[0] == '!') finish(_wa, "Bad answer token");

            finish(_wa, "Unexpected token (expected '?' or '!')");
        }
    }

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

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

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

    const int SUMN = 10000;

    struct Test {
        int n;
        int k;
    };

    vector<Test> tests;
    tests.reserve(200);
    int sum_n = 0;

    auto add_test = [&](int n, int k) -> bool {
        if ((int)tests.size() >= 1000) return false;
        if (n % 2 != 0 || k % 2 != 0) return false;
        if (k < 2 || n < k) return false;
        if (k > 50) return false;
        if (n > 2500) return false;
        if (1LL * k * k < n) return false;
        if (sum_n + n > SUMN) return false;
        tests.push_back({n, k});
        sum_n += n;
        return true;
    };

    add_test(2500, 50);
    add_test(2498, 50);
    add_test(2302, 48);

    int attempts = 0;
    while (sum_n < SUMN && (int)tests.size() < 1000 && attempts < 50000) {
        attempts++;
        int k = rnd.next(1, 25) * 2;
        int r = rnd.next(0, k / 2) * 2;
        if (r == k) r = k - 2;

        int n;
        if (rnd.next(5) == 0) {

            int max_n = k * k;
            int wiggle = rnd.next(0, min(50, max_n / 4));
            n = max_n - 2 * wiggle;
            if (n < k) n = k;
            if (n % 2 != 0) n--;
            if (n < k) n = k;
        } else {

            n = k + r;
        }

        if (n < k) n = k;
        if (n % 2 != 0) n--;
        if (n < k) n = k;
        if (n > k * k) n = k * k;
        if (n > 2500) n = 2500;
        if (n % 2 != 0) n--;
        if (n < k) n = k;

        if (n < k || n > k * k) continue;

        int remaining = SUMN - sum_n;
        if (remaining < 2) break;
        if (n > remaining) {

            int kk = min(50, max(2, (int)std::sqrt((double)remaining) / 2 * 2));
            kk = max(2, min(kk, 50));
            if (kk % 2 != 0) kk--;
            if (kk < 2) break;
            int nn = kk;
            if (nn > remaining) break;
            if (!add_test(nn, kk)) break;
            continue;
        }

        if (!tests.empty() && tests.back().n == n && tests.back().k == k) continue;
        if (!add_test(n, k)) {

            int kk = 2;
            int nn = 2;
            if (!add_test(nn, kk)) break;
        }
    }

    cout << (int)tests.size() << endl;
    for (const auto& tc : tests) {
        int n = tc.n;
        int k = tc.k;
        cout << n << " " << k << endl;

        vector<int> a(n);
        for (int i = 0; i < n; i++) {

            if (rnd.next(5) == 0) a[i] = rnd.next(1, 1024);
            else a[i] = rnd.next(1, 1000000000);
        }
        println(a);
    }

    return 0;
}


This is an interactive problem.

Kira has a hidden positive integer $n$, and Hayato needs to guess it.

Initially, Kira gives Hayato the value $\mathrm{cnt}$ — the number of unit bits in the binary notation of $n$. To guess $n$, Hayato can only do operations of one kind: choose an integer $x$ and subtract it from $n$. Note that after each operation, the number $n$ changes. Kira doesn't like bad requests, so if Hayato tries to subtract a number $x$ greater than $n$, he will lose to Kira. After each operation, Kira gives Hayato the updated value $\mathrm{cnt}$ — the number of unit bits in the binary notation of the updated value of $n$.

Kira doesn't have much patience, so Hayato must guess the original value of $n$ after no more than $30$ operations.

Since Hayato is in elementary school, he asks for your help. Write a program that guesses the number $n$. Kira is an honest person, so he chooses the initial number $n$ before all operations and does not change it afterward.

Input

The input data contains several test cases. The first line contains one integer $t$ ($1 \le t \le 500$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains the number $\mathrm{cnt}$ — the initial number of unit bits in the binary notation $n$.

The hidden integer $n$ satisfies the following constraint: $1 \le n \le 10^9$.

Interaction

To guess $n$, you can perform the operation at most $30$ times. To do that, print a line with the following format: "- x" ($1 \le x \le 10^9$).

After this operation, the number $x$ is subtracted from $n$, and therefore $n$ is changed. If the number $x$ is greater than the current value of $n$, then the request is considered invalid.

After the operation read a line containing a single non-negative integer $\mathrm{cnt}$ — the number of unit bits in the binary notation of the current $n$ after the operation.

When you know the initial value of $n$, print one line in the following format: "! n" ($1 \le n \le 10^9$).

After that, move on to the next test case, or terminate the program if there are none.

If your program performs more than $30$ operations for one test case, subtracts a number $x$ greater than $n$, or makes an incorrect request, then response to the request will be -1, after receiving such response, your program must exit immediately to receive the Wrong Answer verdict. Otherwise, you can get any other verdict.

After printing a query or the answer, 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 documentation for other languages.

Example

Input

```
3

1

0

1

1

0

2

1

0
```

Output

```
- 1

! 1

- 1

- 1

! 2

- 2

- 1

! 3
```

Note

For example, the number of unit bits in number $6$ is $2$, because binary notation of $6$ is $110$. For $13$ the number of unit bits is $3$, because $13_{10} = 1101_2$.

In the first test case, $n = 1$, so the input is the number $1$. After subtracting one from $n$, it becomes zero, so the number of unit bits in it is $0$.

In the third test case, $n = 3$, which in binary representation looks like $3_{10} = 11_2$, so the input is the number of ones, that is $2$. After subtracting $2$, $n = 1$, so the number of unit bits is now $1$. After subtracting one from $n$, it becomes equal to zero.

Note that the blank lines in the input and output examples are shown for clarity and are not present in the actual interaction.

#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());
}

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

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

    int t = inf.readInt();

    query_limit = t * 30LL;
    log_metrics();

    cout << t << endl;

    for (int i = 0; i < t; i++) {

        int initial_n = inf.readInt();
        int current_n = initial_n;

        cout << __builtin_popcount(current_n) << endl;

        int local_queries = 0;

        while (true) {
            string token;

            if (!(cin >> token)) {
                finish(_wa, "Unexpected EOF: expected query or answer");
            }

            if (token == "!") {

                int guess;
                if (!(cin >> guess)) {
                    finish(_wa, "Unexpected EOF: expected number after '!'");
                }

                if (guess == initial_n) {

                    break;
                } else {
                    finish(_wa, format("Wrong Answer: guessed %d, expected %d", guess, initial_n));
                }
            } else {

                long long x = -1;
                bool valid_parse = false;

                if (token == "-" || token == "?") {
                    if (cin >> x) valid_parse = true;
                } else {

                    try {
                        size_t idx;
                        x = stoll(token, &idx);
                        if (idx == token.size()) valid_parse = true;
                    } catch (...) {
                        valid_parse = false;
                    }
                }

                if (!valid_parse) {
                    finish(_wa, format("Invalid token or format: '%s'", token.c_str()));
                }

                if (local_queries >= 30) {

                    cout << -1 << endl;
                    finish(_wa, "Query limit exceeded for test case (max 30)");
                }

                if (x < 1 || x > current_n) {

                    cout << -1 << endl;
                    finish(_wa, format("Invalid query: x=%lld out of range [1, current_n=%d]", x, current_n));
                }

                current_n -= x;
                local_queries++;
                queries++;

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

                cout << __builtin_popcount(current_n) << endl;
            }
        }
    }

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

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

static long long max_queries = 0;
static const long long QUERY_LIMIT = 30;
static const long long HARD_CAP = 200000;
static long long total_ops = 0;

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

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

struct State {
    int original;
    int current;
};

inline int count_bits(int n) {
    return __builtin_popcount(n);
}

vector<int> generate_candidates(int L, int R) {
    set<int> unique_cands;

    auto add = [&](long long x) {
        if (x >= L && x <= R && unique_cands.size() < 2500) {
            unique_cands.insert((int)x);
        }
    };

    for (int k = 0; k < 30; ++k) add(1LL << k);

    for (int k = 1; k <= 30; ++k) add((1LL << k) - 1);

    for (int i = 0; i < 500; ++i) add(rnd.next(L, R));

    for (int i = 0; i < 100; ++i) {
        int k1 = rnd.next(0, 29);
        int k2 = rnd.next(0, 29);
        add((1LL << k1) | (1LL << k2));
    }

    for (int i = 0; i < 100; ++i) {
        int k = rnd.next(10, 29);
        long long v = (1LL << k) - 1;
        int rem = rnd.next(1, 3);
        for (int j = 0; j < rem; ++j) {
            int b = rnd.next(0, k - 1);
            if ((v >> b) & 1) v ^= (1LL << b);
        }
        add(v);
    }

    for(int i=0; i<50; ++i) {
        long long v = 0;
        int start = rnd.next(0, 1);
        int len = rnd.next(1, 29);
        for (int j = 0; j <= len; j++) {
            if (j % 2 == start) v |= (1LL << j);
        }
        add(v);
    }

    while (unique_cands.size() < 2500) {
        int v = rnd.next(L, R);
        add(v);

        if (unique_cands.size() >= (size_t)(R - L + 1)) break;
    }

    return vector<int>(unique_cands.begin(), unique_cands.end());
}

string read_meaningful_line() {
    while (!inf.eof()) {
        string s = inf.readLine();
        string trimmed;
        for (char c : s) if (!isspace(c)) trimmed += c;
        if (!trimmed.empty()) return s;
    }
    return "";
}

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

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

    inf.readLine();

    for (int tc = 0; tc < t; ++tc) {

        string line = read_meaningful_line();
        if (line.empty()) break;

        stringstream ss(line);
        vector<long long> nums;
        long long val;
        while (ss >> val) nums.push_back(val);

        vector<State> candidates;
        if (nums.size() == 1) {

            candidates.push_back({(int)nums[0], (int)nums[0]});
        } else if (nums.size() >= 2) {

            int L = (int)nums[0];
            int R = (int)nums[1];
            vector<int> vals = generate_candidates(L, R);
            for (int v : vals) candidates.push_back({v, v});
        } else {

            candidates.push_back({1, 1});
        }

        vector<vector<State>> buckets(32);
        for (auto& c : candidates) buckets[count_bits(c.current)].push_back(c);

        int best_cnt = -1;
        size_t best_sz = 0;
        for (int i = 0; i < 32; ++i) {
            if (buckets[i].size() > best_sz) {
                best_sz = buckets[i].size();
                best_cnt = i;
            }
        }

        candidates = buckets[best_cnt];
        cout << best_cnt << endl;

        long long current_queries = 0;

        while (true) {

            if (total_ops++ > HARD_CAP) {
                finish(_pe, "Total operations limit exceeded");
            }

            string type;

            char c;
            if (!(cin >> c)) {
                 finish(_pe, "Unexpected EOF (solution terminated early?)");
            }
            cin.putback(c);
            cin >> type;

            if (type == "!") {
                int guess;
                cin >> guess;

                bool all_match = true;
                int mismatch_ex = -1;
                for (auto& st : candidates) {
                    if (st.original != guess) {
                        all_match = false;
                        mismatch_ex = st.original;
                        break;
                    }
                }

                if (!all_match) {
                    finish(_wa, format("Wrong answer. Guess %d, but input consistent with %d", guess, mismatch_ex));
                }

                break;

            } else if (type == "-") {
                long long x_long;
                cin >> x_long;
                int x = (int)x_long;

                current_queries++;
                max_queries = max(max_queries, current_queries);

                if (current_queries % 5 == 0) log_metrics();

                if (current_queries > QUERY_LIMIT) {
                    cout << -1 << endl;
                    finish(_wa, "Query limit exceeded (30 per testcase)");
                }
                if (x < 1 || x > 1000000000) {
                    cout << -1 << endl;
                    finish(_wa, "Invalid query range (x < 1 or x > 10^9)");
                }

                vector<State> valid;
                valid.reserve(candidates.size());
                for (auto& st : candidates) {
                    if (st.current >= x) valid.push_back(st);
                }

                if (valid.empty()) {

                    cout << -1 << endl;
                    finish(_wa, "Subtracted x greater than current n for all feasible candidates");
                }

                for (auto& b : buckets) b.clear();
                for (auto& st : valid) {
                    int nxt = st.current - x;
                    buckets[count_bits(nxt)].push_back({st.original, nxt});
                }

                int best_res = -1;
                size_t best_next_sz = 0;
                for (int i = 0; i < 32; ++i) {
                    if (buckets[i].size() > best_next_sz) {
                        best_next_sz = buckets[i].size();
                        best_res = i;
                    }
                }

                candidates = buckets[best_res];
                cout << best_res << endl;
            } else {
                finish(_pe, "Invalid protocol: expected '-' or '!'");
            }
        }
    }

    finish(_ok, "All test cases passed");
    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");

    int t = opt<int>("t", rnd.next(10, 50));

    cout << t << endl;

    for (int i = 0; i < t; ++i) {
        if (mode == "adp") {

            cout << "1 1000000000" << endl;
        } else {

            int type = rnd.next(1, 10);
            int n = 1;

            if (type == 1) {

                n = rnd.next(1, 1000000000);
            } else if (type == 2) {

                n = rnd.next(1, 100);
            } else if (type == 3) {

                n = rnd.next(1000000000 - 500, 1000000000);
            } else if (type == 4) {

                int k = rnd.next(0, 29);
                n = (1 << k);
            } else if (type == 5) {

                int k = rnd.next(1, 29);
                n = (1 << k) - 1;
            } else if (type == 6) {

                int k1 = rnd.next(0, 29);
                int k2 = rnd.next(0, 29);
                while (k1 == k2) k2 = rnd.next(0, 29);
                n = (1 << k1) | (1 << k2);
            } else if (type == 7) {

                int k = rnd.next(10, 29);
                n = (1 << k) - 1;
                int rem = rnd.next(1, 3);
                for (int j = 0; j < rem; ++j) {
                    int b = rnd.next(0, k - 1);
                    if ((n >> b) & 1) n ^= (1 << b);
                }
            } else if (type == 8) {

                n = 0;
                int start = rnd.next(0, 1);
                int len = rnd.next(1, 29);
                for (int j = 0; j <= len; j++) {
                    if (j % 2 == start) n |= (1 << j);
                }
            } else if (type == 9) {

                n = rnd.next(536870912, 1000000000);
            } else {

                n = rnd.next(1, 1000000000);
            }

            if (n < 1) n = 1;
            if (n > 1000000000) n = 1000000000;

            cout << n << endl;
        }
    }

    return 0;
}


This is the easy version of the problem. The difference between the versions is that in this version, there are no constraints on the sum of the lengths of the articles over all queries.

This is an interactive problem.

The RiOI Team has recently developed a text editor named RiOI Editor. The editor works with exactly one integer parameter $W$ — the width of each line. It is known that $1 \leq W \leq 10^5$.

As you cannot understand the RiOI Language, from your point of view, words differ from each other only by their length. Hence, an article of length $n$ is defined as a sequence $a$ consisting of $n$ positive integers, where $a_i$ is the length of the $i$-th word in the article. The RiOI Editor displays the article $[a_1, a_2,\ldots, a_n]$ on screen as follows:

* If $\max(a_1, a_2, \ldots, a_n) > W$, the editor is unable to display the article;
* Otherwise, the editor is able to display the article by the following process:
  + Initially, $l = 1$, and $s = 0$. During the whole process, $l$ always denotes the current number of lines in the editor, and $s$ always denotes the sum of lengths of words in the last line;
  + Then, for each $1\le i\le n$:
    - If $s + a_i \leq W$, the word is inserted at the end of the current line. Thus, $l$ remains unchanged, and $s$ gets increased by $a_i$.
    - Otherwise, the word is inserted into a new line. Thus, $l$ becomes $l + 1$, and $s$ becomes $a_i$.
  + The number of lines needed to display the article is the final value of $l$.

You are very interested in the editor, so you decide to find out the value of $W$ by inputting some articles into the editor and observing the number of lines needed to display each article.

Formally, you can query the jury at most $2$ times. In each query, you input an article $[a_1, a_2, \ldots, a_n]$ ($1\leq n \leq 10^5$) to the editor, and the jury will respond to you with:

* The number of lines needed to display the article, if the editor is able to display it;
* $0$, if the editor is unable to display the article.

Input

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

Interaction

For each test case, you can make up to $2$ queries to find out the value of $W$. It is guaranteed that $1\leq W\leq 10^5$.

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

* $\texttt{? } n\texttt{ }a_1\texttt{ }a_2\texttt{ }\ldots\texttt{ }a_n$ ($1 \leq n, a_i \leq 10^5$) — the article you input to the editor.

At the end of each query, the jury will print an integer, as described in the statements.

To report that you have found the value of $W$, print a new line in the following format:

* $\texttt{! } W$ — the parameter of the editor.

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

After that, proceed to process the next test case or terminate the program if it was the last test case.

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 adaptive. It means that the value of $W$ may change during the interaction, but it is guaranteed that there is always at least one integer $W$ satisfying all the queries.

Example

Input

```
2

2

1

0
```

Output

```
? 5 1 9 4 6 1

? 2 10 10

! 20
? 1 2

! 1
```

Note

In the first test case:

* For the first query, the total length of the words is $1+9+4+6+1=21$, and the article is displayed in two lines, so $W<21$;
* For the second query, the total length of the words is $10+10=20$, and the article is displayed in one line, so $W\ge 20$.

Thus, we have determined $W = 20$.

In the second test case, the editor cannot display the article in the only query. Thus, $W < 2$, so it can only be $1$.

#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());
}

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

static bool parseLongLongStrict(const string& s, long long& out) {
    if (s.empty()) return false;
    int i = 0;
    bool neg = false;
    if (s[0] == '-') {
        neg = true;
        i = 1;
    }
    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 long long readIntFromCinOrDie(const string& what) {
    string tok;
    if (!readToken(tok)) {
        cout << -1 << endl;
        finish(_pe, "Unexpected EOF while reading " + what);
    }
    long long x = 0;
    if (!parseLongLongStrict(tok, x)) {
        cout << -1 << endl;
        finish(_pe, "Non-integer token while reading " + what);
    }
    return x;
}

static int computeLinesOrZero(const vector<int>& a, int W) {
    int mx = 0;
    for (int x : a) mx = max(mx, x);
    if (mx > W) return 0;
    int lines = 1;
    int s = 0;
    for (int x : a) {
        if (s + x <= W) {
            s += x;
        } else {
            lines++;
            s = x;
        }
    }
    return lines;
}

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

    int t = inf.readInt(1, 10, "t");
    vector<int> hiddenW(t + 1);
    for (int i = 1; i <= t; i++) {
        hiddenW[i] = inf.readInt(1, 100000, "W");
    }

    query_limit = 2LL * t;
    log_metrics();

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

    cout << t << endl;

    for (int tc = 1; tc <= t; tc++) {
        int W = hiddenW[tc];
        bool done = false;

        while (!done) {
            if (queries > hard_cap) {
                cout << -1 << endl;
                finish(_pe, "Hard cap exceeded");
            }

            string cmd;
            if (!readToken(cmd)) {
                cout << -1 << endl;
                finish(_pe, "Unexpected EOF: contestant terminated early");
            }

            if (cmd == "?") {
                long long nll = readIntFromCinOrDie("n");
                if (nll < 1 || nll > 100000) {
                    cout << -1 << endl;
                    finish(_wa, "Invalid query: n out of range");
                }
                int n = (int)nll;
                vector<int> a;
                a.reserve(n);
                for (int i = 0; i < n; i++) {
                    long long xll = readIntFromCinOrDie("a_i");
                    if (xll < 1 || xll > 100000) {
                        cout << -1 << endl;
                        finish(_wa, "Invalid query: a_i out of range");
                    }
                    a.push_back((int)xll);
                }

                int ans = computeLinesOrZero(a, W);
                queries++;

                cout << ans << endl;

            } else if (cmd == "!") {
                long long guess = readIntFromCinOrDie("W");
                if (guess < 1 || guess > 100000) {
                    cout << -1 << endl;
                    finish(_wa, "Invalid answer: W out of range");
                }
                if ((int)guess != W) {
                    cout << -1 << endl;
                    finish(_wa, "Wrong answer");
                }
                done = true;

            } else {
                cout << -1 << endl;
                finish(_pe, "Unknown command token");
            }
        }
    }

    finish(_ok, "OK");
}

#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 string trimCopy(const string& s) {
    size_t i = 0, j = s.size();
    while (i < j && isspace((unsigned char)s[i])) i++;
    while (j > i && isspace((unsigned char)s[j - 1])) j--;
    return s.substr(i, j - i);
}

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

static bool parseLLStrict(const string& s, long long& out) {
    if (s.empty()) return false;
    int i = 0;
    bool neg = false;
    if (s[0] == '-') {
        neg = true;
        i = 1;
        if ((int)s.size() == 1) 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 vector<int> parseIntsFromLine(const string& line) {
    vector<int> v;
    stringstream ss(line);
    long long x;
    while (ss >> x) v.push_back((int)x);
    return v;
}

struct QueryEval {
    int maxA = 0;
    vector<int> a;
    vector<int> memo;
    int maxW = 100000;

    explicit QueryEval(vector<int> arr, int maxW_) : a(std::move(arr)), maxW(maxW_) {
        maxA = 0;
        for (int x : a) maxA = max(maxA, x);
        memo.assign(maxW + 1, -2);
    }

    int linesForW(int W) {
        int lines = 1;
        int s = 0;
        for (int x : a) {
            if (s + x <= W) s += x;
            else {
                lines++;
                s = x;
            }
        }
        return lines;
    }

    int response(int W) {
        if (W < maxA) return 0;
        int& m = memo[W];
        if (m != -2) return m;
        m = linesForW(W);
        return m;
    }

    int linesOnly(int W) {

        int& m = memo[W];
        if (m != -2) return m;
        m = linesForW(W);
        return m;
    }
};

struct Plateau {
    int y = 0;
    int L = 1, R = 0;
};

static Plateau plateauForCandidate(QueryEval& ev, int curL, int curR, int Wc) {
    Plateau p;
    p.y = ev.response(Wc);

    if (p.y == 0) {
        p.L = curL;
        p.R = min(curR, ev.maxA - 1);
        return p;
    }

    int low = max(curL, ev.maxA);
    int high = curR;
    if (low > high) {
        p.L = 1;
        p.R = 0;
        return p;
    }

    int y = p.y;
    int lo = low, hi = Wc;
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        int val = ev.linesOnly(mid);
        if (val <= y) hi = mid;
        else lo = mid + 1;
    }
    int left = lo;

    lo = Wc;
    hi = high;
    while (lo < hi) {
        int mid = (lo + hi + 1) / 2;
        int val = ev.linesOnly(mid);
        if (val >= y) lo = mid;
        else hi = mid - 1;
    }
    int right = lo;

    p.L = left;
    p.R = right;
    return p;
}

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

    const int MAXW = 100000;

    int t = inf.readInt();
    query_limit = 2LL * t;
    log_metrics();

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

    if (!inf.eof()) (void)inf.readLine();

    vector<pair<int,int>> initial(t, {1, MAXW});
    for (int tc = 0; tc < t; tc++) {
        string line;
        while (true) {
            if (inf.eof()) finish(_pe, "unexpected EOF in hidden input");
            line = inf.readLine();
            if (!trimCopy(line).empty()) break;
        }
        auto nums = parseIntsFromLine(line);
        if ((int)nums.size() == 1) {
            int W = nums[0];
            if (W < 1 || W > MAXW) finish(_pe, "hidden W out of range");
            initial[tc] = {W, W};
        } else if ((int)nums.size() == 2) {
            int L = nums[0], R = nums[1];
            if (L < 1 || L > MAXW || R < 1 || R > MAXW) finish(_pe, "hidden interval out of range");
            if (L > R) swap(L, R);
            initial[tc] = {L, R};
        } else {
            finish(_pe, "hidden input line must have 1 or 2 integers");
        }
    }

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

    for (int tc = 0; tc < t; tc++) {
        int curL = initial[tc].first;
        int curR = initial[tc].second;

        while (true) {
            string tok;
            if (!readTokenFromContestant(tok)) finish(_pe, "EOF from contestant");

            if (tok == "?") {
                string sn;
                if (!readTokenFromContestant(sn)) finish(_pe, "missing n");
                long long nll;
                if (!parseLLStrict(sn, nll)) finish(_pe, "invalid n token");
                if (nll < 1 || nll > 100000) finish(_pe, "n out of range");
                int n = (int)nll;

                vector<int> a;
                a.reserve(n);
                for (int i = 0; i < n; i++) {
                    string sa;
                    if (!readTokenFromContestant(sa)) finish(_pe, "missing ai");
                    long long xll;
                    if (!parseLLStrict(sa, xll)) finish(_pe, "invalid ai token");
                    if (xll < 1 || xll > 100000) finish(_pe, "ai out of range");
                    a.push_back((int)xll);
                }

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

                QueryEval ev(std::move(a), MAXW);

                vector<int> candidates;
                candidates.push_back(curL);
                candidates.push_back(curR);
                candidates.push_back((curL + curR) / 2);

                if (curL <= ev.maxA - 1 && ev.maxA - 1 <= curR) candidates.push_back(ev.maxA - 1);
                if (curL <= ev.maxA && ev.maxA <= curR) candidates.push_back(ev.maxA);

                sort(candidates.begin(), candidates.end());
                candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end());

                Plateau best;
                long long bestSize = -1;
                int bestL = -1, bestR = -1, bestY = -1;

                for (int Wc : candidates) {
                    if (Wc < curL || Wc > curR) continue;
                    Plateau p = plateauForCandidate(ev, curL, curR, Wc);
                    if (p.L > p.R) continue;
                    long long sz = 1LL * p.R - p.L + 1;

                    if (sz > bestSize ||
                        (sz == bestSize && (p.L > bestL ||
                                            (p.L == bestL && (p.R > bestR ||
                                                              (p.R == bestR && p.y > bestY)))))) {
                        bestSize = sz;
                        bestL = p.L;
                        bestR = p.R;
                        bestY = p.y;
                        best = p;
                    }
                }

                if (bestSize < 0) {
                    best.y = ev.response(curL);
                    best.L = curL;
                    best.R = curR;
                }

                curL = best.L;
                curR = best.R;

                cout << best.y << "\n";
                cout.flush();
            } else if (tok == "!") {
                string sW;
                if (!readTokenFromContestant(sW)) finish(_pe, "missing final W");
                long long Wll;
                if (!parseLLStrict(sW, Wll)) finish(_pe, "invalid final W token");
                if (Wll < 1 || Wll > MAXW) finish(_wa, "final W out of range");
                int Wans = (int)Wll;

                if (Wans < curL || Wans > curR) finish(_wa, "final W not consistent");
                if (curL != curR) finish(_wa, "W not uniquely determined");

                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 int clampInt(int x, int lo, int hi) {
    if (x < lo) return lo;
    if (x > hi) return hi;
    return x;
}

static int pickStructuredW(int maxW) {

    int mode = rnd.next(0, 99);
    if (mode < 25) {
        return rnd.next(1, min(maxW, 100));
    } else if (mode < 50) {
        int lo = max(1, maxW - 100);
        return rnd.next(lo, maxW);
    } else if (mode < 80) {
        int kMax = 0;
        while ((1 << (kMax + 1)) <= maxW) kMax++;
        int k = rnd.next(0, kMax);
        int base = 1 << k;
        int delta = rnd.next(-1, 1);
        int w = base + delta;
        return clampInt(w, 1, maxW);
    } else {
        return rnd.next(1, maxW);
    }
}

static pair<int,int> pickInterval(int maxW) {
    int mode = rnd.next(0, 99);
    if (mode < 60) {
        return {1, maxW};
    } else if (mode < 75) {
        int len = rnd.next(maxW / 2, maxW);
        int L = rnd.next(1, maxW - len + 1);
        return {L, L + len - 1};
    } else if (mode < 90) {
        int len = rnd.next(1, min(maxW, 50));
        int side = rnd.next(0, 1);
        if (side == 0) return {1, len};
        return {maxW - len + 1, maxW};
    } else {
        int mid = rnd.next(1, maxW);
        int rad = rnd.next(0, min(maxW, 2000));
        int L = max(1, mid - rad);
        int R = min(maxW, mid + rad);
        if (L > R) swap(L, R);
        return {L, R};
    }
}

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

    string mode = opt<string>("mode", "non");
    int maxW = opt<int>("maxw", 100000);
    maxW = clampInt(maxW, 1, 100000);

    cout << 1 << "\n";

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

        try {
            seed = stoll(string(argv[1]));
        } catch (...) {
            seed = 4;
        }
    }

    if (mode == "non") {
        int W;
        if (seed == 1) W = 1;
        else if (seed == 2) W = maxW;
        else if (seed == 3) W = clampInt(50000, 1, maxW);
        else W = pickStructuredW(maxW);

        int forcedW = opt<int>("W", -1);
        if (forcedW != -1) W = clampInt(forcedW, 1, maxW);

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

    if (mode == "adp") {
        int L, R;
        if (seed == 1) { L = 1; R = 1; }
        else if (seed == 2) { L = maxW; R = maxW; }
        else if (seed == 3) { L = 1; R = maxW; }
        else {
            auto iv = pickInterval(maxW);
            L = iv.first;
            R = iv.second;
        }

        int forcedL = opt<int>("L", -1);
        int forcedR = opt<int>("R", -1);
        if (forcedL != -1 || forcedR != -1) {
            if (forcedL == -1) forcedL = 1;
            if (forcedR == -1) forcedR = maxW;
            forcedL = clampInt(forcedL, 1, maxW);
            forcedR = clampInt(forcedR, 1, maxW);
            if (forcedL > forcedR) swap(forcedL, forcedR);
            L = forcedL;
            R = forcedR;
        }

        cout << L << " " << R << "\n";
        return 0;
    }

    int W = pickStructuredW(maxW);
    int forcedW = opt<int>("W", -1);
    if (forcedW != -1) W = clampInt(forcedW, 1, maxW);
    cout << W << "\n";
    return 0;
}