Problem: cf750_f
Difficulty: medium
Categories: graph, math
Time limit: 2000 ms, memory limit: 256 MB

F. New Year and Finding Roots

This is an interactive problem. In the interaction section below you will find the information about flushing the output.

The New Year tree of height *h* is a perfect binary tree with vertices numbered 1 through 2*h* - 1 in some order. In this problem we assume that *h* is at least 2. The drawing below shows one example New Year tree of height 3:

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

Polar bears love decorating the New Year tree and Limak is no exception. To decorate the tree, he must first find its root, i.e. a vertex with exactly two neighbours (assuming that *h* ≥ 2). It won't be easy because Limak is a little bear and he doesn't even see the whole tree. Can you help him?

There are *t* testcases. In each testcase, you should first read *h* from the input. Then you can ask at most 16 questions of format "? x" (without quotes), where *x* is an integer between 1 and 2*h* - 1, inclusive. As a reply you will get the list of neighbours of vertex *x* (more details in the "Interaction" section below). For example, for a tree on the drawing above after asking "? 1" you would get a response with 3 neighbours: 4, 5 and 7. Your goal is to find the index of the root *y* and print it in the format "! y". You will be able to read *h* for a next testcase only after printing the answer in a previous testcase and flushing the output.

Each tree is fixed from the beginning and it doesn't change during your questions.

Input

The first line of the input contains a single integer *t* (1 ≤ *t* ≤ 500) — the number of testcases.

At the beginning of each testcase you should read from the input a single integer *h* (2 ≤ *h* ≤ 7) — the height of the tree. You can't read the value of *h* in a next testcase until you answer a previous testcase.

Interaction

To ask a question about neighbours of vertex *x*, print "? x" (without quotes) on a separate line. Note, you must print an end-of-line character after the last character of the line and flush your output to get a response.

The response will consist of two lines. The first line will contain a single integer *k* (1 ≤ *k* ≤ 3) — the number of neighbours of vertex *x*. The second line will contain *k* distinct integers *t*1, ..., *t**k* (1 ≤ *t*1 < ... < *t**k* ≤ 2*h* - 1) — indices of neighbours of vertex *x*, gives in the increasing order.

After asking at most 16 questions you have to say *y* — the index of the root. Print "! y" (without quotes) and an end-of-line character, and flush the output.

Each tree is fixed from the beginning and it doesn't change during your questions.

You can get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output.

To flush you can use (just printing a query/answer and end-of-line):

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

In any moment if the program reads *h* = 0 or *k* = 0 it should immediately terminate normally (for example, calling exit(0)). It means that the system detected incorrect request/output from your program and printed 0 because if can't process your requests anymore. In this case you'll receive verdict "Wrong Answer", but if you ignore case *h* = 0 or *k* = 0 it could lead to "Runtime Error", "Time/Memory limit exceeded" or any other verdict because your program could read a trash from the closed input stream.

Examples

Input

```
1  
3  
3  
4 5 7  
2  
1 2  
1  
2
```

Output

```
? 1  
? 5  
? 6  
! 5
```

Input

```
2  
2  
1  
3  
2  
1 2  
2  
1 2  
4  
3  
3 12 13
```

Output

```
? 1  
? 3  
? 3  
! 3  
? 6  
! 1
```

Note

In the first sample, a tree corresponds to the drawing from the statement.

In the second sample, there are two two testcases. A tree in the first testcase has height 2 and thus 3 vertices. A tree in the second testcase has height 4 and thus 15 vertices. You can see both trees on the drawing below.

 ![](https://espresso.codeforces.com/9db3581501e9c1bf651760cf0a6824c0ac95dc52.png)

Non-adaptive interactor (C++):
#include "testlib.h"
#include <bits/stdc++.h>

using namespace std;



static long long queries_metric = 0;

static long long query_limit_metric = 16;

static void log_metrics() {
    try {
        tout << "queries=" << queries_metric << endl;
        tout << "query_limit=" << query_limit_metric << 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();
    
    
    cout << t << endl;

    for (int i = 0; i < t; i++) {
        
        int h = inf.readInt();
        int n = (1 << h) - 1;

        
        vector<vector<int>> adj(n + 1);
        for (int j = 0; j < n - 1; j++) {
            int u = inf.readInt();
            int v = inf.readInt();
            adj[u].push_back(v);
            adj[v].push_back(u);
        }

        
        int real_root = -1;
        for (int u = 1; u <= n; u++) {
            if (adj[u].size() == 2) {
                real_root = u;
                break;
            }
        }

        if (real_root == -1) {
            finish(_fail, "Generator error: No root of degree 2 found in the tree.");
        }

        
        cout << h << endl;

        long long current_case_queries = 0;
        
        
        while (true) {
            string token;
            if (!(cin >> token)) {
                finish(_wa, "Unexpected EOF (contestant output ended prematurely)");
            }

            if (token == "!") {
                
                int y;
                if (!(cin >> y)) {
                    finish(_wa, "Expected integer answer after '!'");
                }

                if (y == real_root) {
                    
                    break;
                } else {
                    finish(_wa, format("Wrong answer: guessed %d, expected %d", y, real_root));
                }
            } else {
                
                int x = -1;
                if (token == "?") {
                    if (!(cin >> x)) {
                        finish(_wa, "Expected integer query index after '?'");
                    }
                } else {
                    
                    try {
                        size_t pos;
                        x = stoi(token, &pos);
                        if (pos != token.size()) {
                            finish(_wa, "Invalid query token (garbage after integer)");
                        }
                    } catch (...) {
                        finish(_wa, format("Invalid token '%s': expected '?', '!', or integer", token.c_str()));
                    }
                }

                
                if (x < 1 || x > n) {
                    finish(_wa, format("Query index %d out of bounds [1, %d]", x, n));
                }

                
                current_case_queries++;
                queries_metric = max(queries_metric, current_case_queries);

                
                if (current_case_queries % 10 == 0) {
                    log_metrics();
                }

                
                
                if (current_case_queries > 200) {
                    finish(_pe, "Hard query limit exceeded (200) for a single testcase");
                }

                
                int k = (int)adj[x].size();
                sort(adj[x].begin(), adj[x].end());

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

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


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

using namespace std;


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






const long long HARD_CAP = 20000; 

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

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







vector<int> get_neighbors_pos(int pos, int h) {
    vector<int> neis;
    if (pos > 1) neis.push_back(pos / 2);
    int left = pos * 2;
    int right = pos * 2 + 1;
    int max_node = (1 << h) - 1;
    if (left <= max_node) neis.push_back(left);
    if (right <= max_node) neis.push_back(right);
    sort(neis.begin(), neis.end());
    return neis;
}


vector<int> input_data;
size_t input_ptr = 0;

int read_int_from_buffer() {
    if (input_ptr >= input_data.size()) __testlib_fail("Input exhausted unexpectedly");
    return input_data[input_ptr++];
}


struct AdaptiveState {
    int h;
    int n;
    map<int, int> node_to_pos; 
    map<int, int> pos_to_node; 
    set<int> used_labels;
    set<int> used_positions;

    void init(int _h) {
        h = _h;
        n = (1 << h) - 1;
        node_to_pos.clear();
        pos_to_node.clear();
        used_labels.clear();
        used_positions.clear();
    }

    int get_pos(int label) {
        if (node_to_pos.count(label)) return node_to_pos[label];
        
        
        
        
        vector<int> candidates;
        for (int p = 1; p <= n; ++p) {
            if (used_positions.find(p) == used_positions.end()) {
                candidates.push_back(p);
            }
        }
        
        if (candidates.empty()) __testlib_fail("No positions left (internal error)");
        
        
        vector<int> non_root;
        for (int c : candidates) {
            if (c != 1) non_root.push_back(c);
        }

        int chosen = -1;
        if (!non_root.empty()) {
            chosen = non_root[rnd.next(0, (int)non_root.size() - 1)];
        } else {
            
            chosen = 1;
        }

        assign(label, chosen);
        return chosen;
    }

    void assign(int label, int pos) {
        if (node_to_pos.count(label) && node_to_pos[label] != pos) 
            __testlib_fail("Inconsistent assignment");
        if (pos_to_node.count(pos) && pos_to_node[pos] != label)
            __testlib_fail("Inconsistent assignment");
            
        node_to_pos[label] = pos;
        pos_to_node[pos] = label;
        used_labels.insert(label);
        used_positions.insert(pos);
    }

    
    int ensure_label(int n_pos) {
        if (pos_to_node.count(n_pos)) return pos_to_node[n_pos];

        
        
        vector<int> available;
        for (int i = 1; i <= n; ++i) {
            if (used_labels.find(i) == used_labels.end()) {
                available.push_back(i);
            }
        }
        if (available.empty()) __testlib_fail("No labels left (internal error)");
        
        int lbl = available[rnd.next(0, (int)available.size() - 1)];
        assign(lbl, n_pos);
        return lbl;
    }
};

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

    
    
    while (!inf.seekEof()) {
        input_data.push_back(inf.readInt());
    }

    if (input_data.empty()) __testlib_fail("Empty input");

    int t = input_data[input_ptr++];
    
    
    
    bool adaptive_mode = (input_data.size() == (size_t)(1 + t));

    cout << t << endl; 

    for (int i = 0; i < t; ++i) {
        int h = read_int_from_buffer();
        int n = (1 << h) - 1;
        cout << h << endl; 

        
        vector<vector<int>> adj;
        int fixed_root = -1;

        
        AdaptiveState adpState;

        if (adaptive_mode) {
            adpState.init(h);
        } else {
            
            adj.assign(n + 1, vector<int>());
            
            for (int k = 0; k < n - 1; ++k) {
                int u = read_int_from_buffer();
                int v = read_int_from_buffer();
                adj[u].push_back(v);
                adj[v].push_back(u);
            }
            
            for (int u = 1; u <= n; ++u) {
                if (adj[u].size() == 2) {
                    fixed_root = u;
                    break;
                }
            }
            if (fixed_root == -1) {
                
                finish(_wa, "Invalid test case: no root found in fixed graph");
            }
            
            for(auto& row : adj) sort(row.begin(), row.end());
        }

        int local_queries = 0;
        bool solved = false;

        while (true) {
            
            string type;
            if (!(cin >> type)) finish(_wa, "Unexpected EOF from contestant");
            
            if (type == "!") {
                int ans;
                if (!(cin >> ans)) finish(_wa, "Expected answer integer");
                
                if (adaptive_mode) {
                    
                    if (adpState.pos_to_node.count(1)) {
                        
                        int actual_root = adpState.pos_to_node[1];
                        if (ans != actual_root) {
                            finish(_wa, format("Wrong answer. Expected %d, found %d", actual_root, ans));
                        }
                    } else {
                        
                        
                        if (adpState.node_to_pos.count(ans)) {
                            finish(_wa, format("Wrong answer. Node %d is at position %d, not root", ans, adpState.node_to_pos[ans]));
                        }
                        
                        
                        
                        
                        int assigned_count = adpState.used_labels.size();
                        if (assigned_count < n) {
                             
                             
                             
                             finish(_wa, "Wrong answer. You guessed an unvisited node, but it wasn't uniquely determined.");
                        } else {
                            
                        }
                    }
                } else {
                    
                    if (ans != fixed_root) {
                        finish(_wa, format("Wrong answer. Expected %d, found %d", fixed_root, ans));
                    }
                }
                
                solved = true;
                break; 
            } else if (type == "?") {
                int u;
                if (!(cin >> u)) finish(_wa, "Expected query integer");
                
                
                if (u < 1 || u > n) finish(_wa, format("Invalid query vertex %d (n=%d)", u, n));
                
                queries++;
                local_queries++;
                log_metrics(); 

                if (local_queries > 16) {
                    finish(_wa, "Query limit exceeded (16 per testcase)");
                }
                if (queries > HARD_CAP) {
                    finish(_pe, "Hard query limit exceeded");
                }

                vector<int> neighbors;
                if (adaptive_mode) {
                    
                    int pos = adpState.get_pos(u);
                    
                    vector<int> n_positions = get_neighbors_pos(pos, h);
                    
                    for (int np : n_positions) {
                        neighbors.push_back(adpState.ensure_label(np));
                    }
                    sort(neighbors.begin(), neighbors.end());
                } else {
                    neighbors = adj[u];
                }

                cout << neighbors.size();
                for (int v : neighbors) cout << " " << v;
                cout << endl; 

            } else {
                finish(_wa, "Invalid token type: " + type);
            }
        }
    }

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


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

using namespace std;

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

    
    
    string mode = opt<string>("mode", "non");
    
    int t_arg = opt<int>("t", -1);
    
    int h_arg = opt<int>("h", -1);

    
    
    long long seed_val = 0;
    if (argc > 1) {
        seed_val = atoll(argv[1]); 
    }

    
    int t = (t_arg != -1) ? t_arg : 1;
    
    cout << t << "\n";

    for (int i = 0; i < t; ++i) {
        int h;
        if (h_arg != -1) {
            h = h_arg;
        } else {
            
            if (seed_val == 1) h = 2;       
            else if (seed_val == 2) h = 3;  
            else if (seed_val == 3) h = 7;  
            else {
                
                
                int r = rnd.next(1, 100);
                if (r <= 60) h = 7;         
                else if (r <= 85) h = 6;    
                else h = rnd.next(2, 5);    
            }
        }

        cout << h << "\n";

        if (mode == "non") {
            
            
            int n = (1 << h) - 1;
            vector<pair<int, int>> edges;
            
            
            
            
            int internal_nodes = (1 << (h - 1)) - 1;
            for (int u = 1; u <= internal_nodes; ++u) {
                edges.push_back({u, 2 * u});
                edges.push_back({u, 2 * u + 1});
            }

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

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

            
            for (const auto& edge : edges) {
                cout << p[edge.first] << " " << p[edge.second] << "\n";
            }
        }
        
        
    }

    return 0;
}