# This is an interactive problem.

Consider an $n \times n$ chessboard, where its rows are numbered 1 to $n$ from top to bottom, and its columns are numbered 1 to $n$ from left to right. The square on the $x$ -th row and the $y$ -th column is denoted as $( x , y )$ and is either empty or occupied by a neutral rook. According to the rules of chess, a rook can move any number of squares along a row or column in one step but cannot leap over other pieces. In this scenario, the control area of a rook consists of the square it occupies and the squares it can reach in one step.

![](images/2329d7eddcb7513f926993d4b549ab7546b1f1ee62c272881a6758dbc073b5ae.jpg)
Figure 1: The control area of the rook at (3,4)

A square is considered “controlled” if and only if it belongs to one or more control areas. The known information is that all squares are controlled initially, so clearly, there are at least $n$ rooks on the chessboard. Whether each square is empty or occupied by a rook, however, is unknown to you. Your task is to locate at least $n$ of the hidden rooks by making no more than $\lceil \log _ { 2 } n \rceil + 2$ queries.

In each query, you need to split the chessboard into two tiers by determining which squares should comprise the upper tier and which the lower tier. The rooks are only allowed to move within the tier to which they belong, and they can leap over gaps but cannot leap over other pieces in the same tier. The definitions of control areas and controlled squares do not change. As a response, the interactor will inform you whether each square is controlled after the splitting. Then, the chessboard will return to the initial state.

![](images/dda6008c22fd6d64a054b9add84df688b040427045e1c3c3b07a591bb6537128.jpg)
Figure 2: Split the T-shaped upper tier out of the chessboard

You may assume that the locations of all the rooks are fixed in advance. Note again that it is not necessary to find all the rooks when the actual number of rooks is greater than $n$ .

# Interaction Protocol

The first line contains an integer $T$ ( $1 \le T \le 1 0 ^ { 4 }$ ), denoting the number of test cases.

The first line of each test case contains an integer $n$ ( $3 \leq n \leq 5 0 0$ ), denoting the size of the chessboard.
It is guaranteed that the number of test cases that $n \geq 1 0$ does not exceed 5.

To initiate an interaction behavior, you should firstly print a character opt $( o p t \in \{ { \stackrel { \cdot \cdot } { . } } , { \stackrel { \cdot } { . } } \} )$ in one line and then print an $n \times n$ binary matrix (in $n$ lines, each containing a binary string). After printing the binary matrix, do not forget to flush the output. To do this, use fflush(stdout) or cout.flush() in $\mathrm { C } + +$ , System.out.flush() in Java, or stdout.flush() in Python.

$o p t = { } ^ { \cdot } ?$ ’ represents making a query. If the character in the $x$ -th row and $y$ -th column of your binary matrix is $\cdot _ { 1 } \cdot \mathbf { \tau }$ , the square $( x , y )$ will comprise the upper tier, or otherwise, it will comprise the lower tier. The interactor will return an integer code $\mathit { c o d e } \in \{ 0 , 1 \}$ ) in one line. If $c o d e = 1$ , you will get Wrong Answer because you made more than $\lceil \log _ { 2 } n \rceil + 2$ queries. If $c o d e = 0$ , you will then receive another $n \times n$ binary matrix from the interactor. If the character in the $x$ -th row and $y$ -th column of the received binary matrix is $\cdot _ { 1 } \cdot$ , the square $( x , y )$ is controlled after the splitting, or otherwise, it is uncontrolled.

$o p t = { } ^ { \cdot } !$ ’ represents answering the locations. If the character in the $x$ -th row and $y$ -th column of your binary matrix is $\mathit { \Omega } _ { 1 } \mathit { \Omega } _ { 1 } \mathit { \Omega } _ { 1 }$ , the square $( x , y )$ is occupied by a rook in your judgment, or otherwise, whether it is empty or occupied by a rook will not affect the verification of your answer. The interactor will return an integer code ( $c o d e \in \{ 0 , 1 \}$ ) in one line. If $c o d e = 1$ , you will get Wrong Answer because your answer failed to match the actual locations of the rooks or you did not find enough rooks. If $c o d e = 0$ , you will enter the next test case if the current test case is not the last one.

If you attempt to print opt that is neither ‘ ?’ nor ‘ !’, or if your binary matrix is badly formatted, such as some of the $n$ rows has a length other than $n$ or contains a character that is neither $ { \mathbf { \cdot } } _ { 0 } ,$ nor $\cdot _ { 1 } \cdot$ , the interactor will return $c o d e = - 1$ and you will get Wrong Answer as well.

Please terminate your program immediately when you receive some code other than 0 to avoid any unexpected verdicts.

# Example

standard input	standard output

1 3

	？ 101

	000

	101

0

110

111

111	？

	111

	100

0	100

111

111

101

	！

	010

	001

	100

0

# Note

The blank lines in the sample case are added for readability. In your output, extra spaces or blank lines will be ignored.

#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();
    cout << T << endl;

    for (int t = 0; t < T; ++t) {
        int n = inf.readInt();
        vector<string> hidden_board(n);
        for (int i = 0; i < n; ++i) {
            hidden_board[i] = inf.readToken();
        }

        cout << n << endl;

        int current_limit = (int)ceil(log2((double)n)) + 2;
        query_limit += current_limit;

        int current_queries = 0;
        bool case_solved = false;

        while (true) {
            string token;

            if (!(cin >> token)) {
                finish(_wa, "Unexpected EOF from solution (expected opt)");
            }

            if (token == "?") {

                vector<string> query_mask(n);
                for(int i = 0; i < n; ++i) {
                    if (!(cin >> query_mask[i])) finish(_wa, "EOF reading query matrix");
                    if ((int)query_mask[i].size() != n) finish(_wa, "Invalid query matrix dimension");
                    for(char c : query_mask[i]) {
                        if (c != '0' && c != '1') finish(_wa, "Invalid char in query matrix");
                    }
                }

                current_queries++;
                queries++;
                log_metrics();

                if (current_queries > current_limit) {
                    cout << 1 << endl;
                    finish(_wa, "Query limit exceeded");
                }

                vector<int> row_tier0(n, 0), row_tier1(n, 0);
                vector<int> col_tier0(n, 0), col_tier1(n, 0);

                for(int r = 0; r < n; ++r) {
                    for(int c = 0; c < n; ++c) {
                        if (hidden_board[r][c] == '1') {
                            char tier = query_mask[r][c];
                            if (tier == '0') {
                                row_tier0[r] = 1;
                                col_tier0[c] = 1;
                            } else {
                                row_tier1[r] = 1;
                                col_tier1[c] = 1;
                            }
                        }
                    }
                }

                vector<string> response(n, string(n, '0'));
                for(int r = 0; r < n; ++r) {
                    for(int c = 0; c < n; ++c) {
                        bool controlled = false;
                        if (hidden_board[r][c] == '1') {
                            controlled = true;
                        } else {
                            char tier = query_mask[r][c];
                            if (tier == '0') {
                                if (row_tier0[r] || col_tier0[c]) controlled = true;
                            } else {
                                if (row_tier1[r] || col_tier1[c]) controlled = true;
                            }
                        }
                        response[r][c] = controlled ? '1' : '0';
                    }
                }

                cout << 0 << endl;
                for(int i = 0; i < n; ++i) cout << response[i] << endl;
                cout.flush();

            } else if (token == "!") {

                vector<string> ans_mask(n);
                for(int i = 0; i < n; ++i) {
                    if (!(cin >> ans_mask[i])) finish(_wa, "EOF reading answer matrix");
                    if ((int)ans_mask[i].size() != n) finish(_wa, "Invalid answer matrix dimension");
                    for(char c : ans_mask[i]) {
                        if (c != '0' && c != '1') finish(_wa, "Invalid char in answer matrix");
                    }
                }

                int found_cnt = 0;
                bool false_positive = false;

                for(int r = 0; r < n; ++r) {
                    for(int c = 0; c < n; ++c) {
                        if (ans_mask[r][c] == '1') {
                            if (hidden_board[r][c] == '1') {
                                found_cnt++;
                            } else {
                                false_positive = true;
                            }
                        }
                    }
                }

                if (!false_positive && found_cnt >= n) {
                    cout << 0 << endl;
                    case_solved = true;
                    break;
                } else {
                    cout << 1 << endl;
                    finish(_wa, "Incorrect answer: false positive or fewer than n rooks found");
                }

            } else {

                cout << -1 << endl;
                finish(_wa, "Invalid operator token (expected ? or !)");
            }
        }
    }

    finish(_ok, "All 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 n = opt<int>("n", 0);

    if (n == 0) {

        int type = rnd.next(1, 100);
        if (type <= 5) n = rnd.next(3, 10);
        else if (type <= 20) n = rnd.next(11, 50);
        else n = rnd.next(51, 500);
    }

    if (n < 3) n = 3;
    if (n > 500) n = 500;

    vector<string> board(n, string(n, '0'));

    int strategy;
    if (mode == "adp") {

        int r = rnd.next(0, 2);
        if (r == 0) strategy = 0;
        else if (r == 1) strategy = 3;
        else strategy = 4;
    } else {

        strategy = rnd.next(0, 5);
    }

    if (strategy == 0) {

        vector<int> p(n);
        iota(p.begin(), p.end(), 0);
        shuffle(p.begin(), p.end());
        for (int i = 0; i < n; i++) {
            board[i][p[i]] = '1';
        }
    } else if (strategy == 1) {

        for (int i = 0; i < n; i++) {
            int count = rnd.next(1, 2);
            for (int k = 0; k < count; k++) {
                board[i][rnd.next(0, n - 1)] = '1';
            }
        }
    } else if (strategy == 2) {

        for (int j = 0; j < n; j++) {
            int count = rnd.next(1, 2);
            for (int k = 0; k < count; k++) {
                board[rnd.next(0, n - 1)][j] = '1';
            }
        }
    } else if (strategy == 3) {

        int c = rnd.next(0, n - 1);
        for (int i = 0; i < n; i++) board[i][c] = '1';

        int noise = rnd.next(0, n);
        for (int k = 0; k < noise; k++) {
            board[rnd.next(0, n - 1)][rnd.next(0, n - 1)] = '1';
        }
    } else if (strategy == 4) {

        int r = rnd.next(0, n - 1);
        for (int j = 0; j < n; j++) board[r][j] = '1';

        int noise = rnd.next(0, n);
        for (int k = 0; k < noise; k++) {
            board[rnd.next(0, n - 1)][rnd.next(0, n - 1)] = '1';
        }
    } else {

        if (rnd.next(0, 1)) {

            for (int i = 0; i < n; i++) board[i][rnd.next(0, n - 1)] = '1';
        } else {

            for (int j = 0; j < n; j++) board[rnd.next(0, n - 1)][j] = '1';
        }

        int count = rnd.next(n, n * n / 2);
        for (int k = 0; k < count; k++) {
            board[rnd.next(0, n - 1)][rnd.next(0, n - 1)] = '1';
        }
    }

    cout << 1 << "\n";
    cout << n << "\n";
    for (int i = 0; i < n; i++) {
        cout << board[i] << "\n";
    }

    return 0;
}


![](images/208e74b2f332c95161b3e998ea0b496ef8df95cf05a97a2fb22b68ac19de5661.jpg)

As you are studying ancient greek mythology, you stumble upon the legend of Phaethon, son of Helios. After being recognized by Helios as his son, he asks him to drive his chariot. Despite the warnings of Helios that only he can control the horses, Helios obliges, giving Phaethon the control of the chariot.

Tragically, Phaethon loses control of the chariot, which gets too close to the Earth and burns it.

However, you wonder if maybe the story could have ended differently. If Phaethon reaches the temple of Helios, then the chariot can be stopped by Helios himself. For that, you create a model that fits the story.

Greece can be represented as a 2D infinite grid, with Phaethon and its chariot starting at coordinate $( 0 , 0 )$ , facing the $\mathrm { O x }$ axis in the direction of increasing X. The temple of Helios is placed in an unknown position $( X , Y )$ on this 2D grid. Initially, the velocity V of the chariot is 1.

At each timestep, the following happens in order:

1. Phaethon does one of the following 3 actions: turn the chariot left 90 degrees, continue facing front, or turn the chariot right 90 degrees;
2. The chariot moves V units in the direction it is facing;
3. $V$ is increased by 1;
4. The Oracle tells Phaethon the Manhattan distance between his position and the position of the temple of Helios.

The Manhattan distance between (X1, Y1) and (X2, Y2) is $| X 1 - X 2 | + | Y 1 - Y 2 |$ .

If the velocity ever reaches $2 \times 1 0 ^ { 4 } .$ , the chariot gets uncontrolled and too close to the earth. If at the end of a step, the chariot is in $( X , Y )$ , the chariot is stopped.

# Input and Output

This is an interactive problem. As such, no initial input is provided in this problem, and you get to ask a question first.

At each step, you must print a line to act on the direction of the chariot. This line must follow the description "? c" followed by a newline, where c is either L to rotate counterclockwise, R to rotate clockwise, or F to keep the direction unchanged. If it does not respect this format, you will receive a WRONG-ANSWER verdict.

After sending a line, you must always flush the output. Otherwise, you will get the verdict TIMELIMIT.

The oracle then prints a single integer, that you can read on the standard input, denoting the Manhattan distance between your new position (after moving V units in the specified direction) and the temple. V is increased after updating your position.

If this distance is 0, it means you arrived to the temple of Helios and thus should stop interaction immediately (exiting your program), receiving an ACCEPTED verdict.

Notice that you must be in the temple after your move, just flying above the temple with the chariot does not count.

If your velocity ever reaches $2 \times 1 0 ^ { 4 }$ , you will receive the verdict WRONG-ANSWER.

# Limits

$$
 \begin{array} { l } { { \bullet } } \end{array} | X | \leqslant 1 0 ^ { 6 }
$$

# Sample interaction

In this section, to clarify what the input and output should be, $^ { \prime \prime } < ^ { \prime \prime }$ is printed before what your program can read on standard input and $^ { \prime \prime } > { ^ { \prime \prime } }$ is printed before what your program should output. Do not include these characters in your real input/output.

In this example, the temple of Helios (whose position you must guess) is located at $\mathrm { X } { = } 1$ , $\Upsilon { = } 5$ . The left column is the I/O. The right column is the state of the chariot after the requested move happened.

$> \ ? \ \mathtt { F }$ Chariot moves to $( 1 , 0 )$ , orientation $=$ right, $V = 2$ $< ~ 5$ Distance from (1,0) to (1,5) is 5 $> \ ? \ \nsim$ Chariot moves to (1, 2), orientation $\mathsf { \Pi } _ { 1 } = \mathsf { u p } , V = 3$ $< ~ 3$ Distance from (1,2) to (1,5) is 3 $> \ ? \ \mathtt { F }$ Chariot moves to (1, 5), orientatio $\mathsf { \Omega } _ { 1 } = \mathsf { u p } , V = 4$ $< ~ 0$ Success

An interactive Python script where you can enter commands and see how the judge would respond is also available on the Web version of this problem.

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

using namespace std;

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

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

    long long tx = inf.readLong();
    long long ty = inf.readLong();

    long long cx = 0;
    long long cy = 0;
    long long v = 1;

    int dir = 0;

    long long dx[] = {1, 0, -1, 0};
    long long dy[] = {0, 1, 0, -1};

    while (true) {

        if (v >= 20000) {
            finish(_wa, "Velocity reached 20000 limit before finding the temple.");
        }

        string token;

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

        char c = ' ';

        if (token == "?") {
            string next_token;
            if (!(cin >> next_token)) {
                finish(_wa, "Unexpected EOF after '?'.");
            }
            if (next_token.size() != 1) {
                finish(_wa, "Invalid move format: expected single character after '?'.");
            }
            c = next_token[0];
        } else if (token == "!") {

            finish(_wa, "Invalid token '!'. Expected move '? c' or 'c'.");
        } else {

            if (token.size() != 1) {
                finish(_wa, "Invalid move format: expected single character.");
            }
            c = token[0];
        }

        if (c == 'L') {

            dir = (dir + 1) % 4;
        } else if (c == 'R') {

            dir = (dir + 3) % 4;
        } else if (c == 'F') {

        } else {
            finish(_wa, format("Unknown move character '%c'. Expected L, R, or F.", c));
        }

        cx += dx[dir] * v;
        cy += dy[dir] * v;

        v++;
        queries++;

        if (queries % 100 == 0) {
            log_metrics();
        }

        long long dist = std::abs(cx - tx) + std::abs(cy - ty);

        if (dist == 0) {
            cout << 0 << endl;
            finish(_ok, format("Reached temple at (%lld, %lld).", cx, cy));
        }

        cout << dist << endl;

        if (v >= 20000) {
            finish(_wa, "Velocity reached 20000 limit.");
        }

        if (queries > 25000) {
            finish(_pe, "Too many queries (hard cap).");
        }
    }

    return 0;
}

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

static long long queries = 0;

static long long query_limit = 19999;
static const long long HARD_CAP = 40000;

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

static long long manhattan(long long x1, long long y1, long long x2, long long y2) {
    return abs(x1 - x2) + abs(y1 - y2);
}

static bool adaptive_mode = false;
static Point fixed_target = {0, 0};
static vector<Point> candidates;
static long long minX = -1000000, maxX = 1000000;
static long long minY = -1000000, maxY = 1000000;

static long long cx = 0, cy = 0;
static int cdir = 0;
static long long velocity = 1;

static int dx[] = {1, 0, -1, 0};
static int dy[] = {0, 1, 0, -1};

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

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

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

    string token = inf.readToken();
    if (token == "ADAPTIVE") {
        adaptive_mode = true;
        minX = inf.readLong();
        maxX = inf.readLong();
        minY = inf.readLong();
        maxY = inf.readLong();

        int num_initial = 10000;
        candidates.reserve(num_initial + 100);

        candidates.push_back({minX, minY});
        candidates.push_back({minX, maxY});
        candidates.push_back({maxX, minY});
        candidates.push_back({maxX, maxY});
        candidates.push_back({0, 0});

        for (int i = 0; i < num_initial; ++i) {
            if (i < 1000) {

                int side = rnd.next(4);
                long long px, py;
                if (side == 0) { px = minX; py = rnd.next(minY, maxY); }
                else if (side == 1) { px = maxX; py = rnd.next(minY, maxY); }
                else if (side == 2) { py = minY; px = rnd.next(minX, maxX); }
                else { py = maxY; px = rnd.next(minX, maxX); }
                candidates.push_back({px, py});
            } else {

                candidates.push_back({rnd.next(minX, maxX), rnd.next(minY, maxY)});
            }
        }

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

    } else {
        adaptive_mode = false;
        long long x = stoll(token);
        long long y = inf.readLong();
        fixed_target = {x, y};
    }

    log_metrics();

    while (true) {

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

        char q_type;
        if (!(cin >> q_type)) {

            finish(_wa, "Unexpected EOF while reading query type");
        }
        if (q_type != '?') {
            finish(_wa, "Query must start with '?'");
        }

        string cmd_str;
        if (!(cin >> cmd_str)) {
            finish(_wa, "Unexpected EOF while reading command");
        }
        if (cmd_str.size() != 1) {
            finish(_wa, "Command must be a single character");
        }
        char cmd = cmd_str[0];

        if (cmd == 'L') {
            cdir = (cdir + 1) % 4;
        } else if (cmd == 'R') {
            cdir = (cdir + 3) % 4;
        } else if (cmd == 'F') {

        } else {
            finish(_wa, "Invalid command (expected L, R, or F)");
        }

        cx += dx[cdir] * velocity;
        cy += dy[cdir] * velocity;
        velocity++;
        queries++;

        long long response_dist = 0;

        if (!adaptive_mode) {
            response_dist = manhattan(cx, cy, fixed_target.x, fixed_target.y);
        } else {

            static vector<pair<long long, int>> dist_map;
            dist_map.clear();
            dist_map.reserve(candidates.size());

            for (int i = 0; i < (int)candidates.size(); ++i) {
                long long d = manhattan(cx, cy, candidates[i].x, candidates[i].y);
                dist_map.push_back({d, i});
            }
            sort(dist_map.begin(), dist_map.end());

            long long best_dist = -1;
            int max_count = -1;

            long long cur_dist = -1;
            int cur_count = 0;

            for (size_t i = 0; i < dist_map.size(); ++i) {
                if (i == 0 || dist_map[i].first != cur_dist) {
                    if (i > 0) {
                        if (cur_count > max_count) {
                            max_count = cur_count;
                            best_dist = cur_dist;
                        } else if (cur_count == max_count) {
                            if (cur_dist > best_dist) best_dist = cur_dist;
                        }
                    }
                    cur_dist = dist_map[i].first;
                    cur_count = 1;
                } else {
                    cur_count++;
                }
            }

            if (cur_count > max_count) {
                max_count = cur_count;
                best_dist = cur_dist;
            } else if (cur_count == max_count) {
                if (cur_dist > best_dist) best_dist = cur_dist;
            }

            vector<Point> next_candidates;
            next_candidates.reserve(max_count);

            auto it = lower_bound(dist_map.begin(), dist_map.end(), make_pair(best_dist, -1));
            while (it != dist_map.end() && it->first == best_dist) {
                next_candidates.push_back(candidates[it->second]);
                it++;
            }
            candidates = move(next_candidates);
            response_dist = best_dist;
        }

        if (queries % 100 == 0) {
            log_metrics();
        }

        cout << response_dist << endl;

        if (response_dist == 0) {
            finish(_ok, "Target found");
        }

    }

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

    if (mode == "adp") {
        cout << "ADAPTIVE -1000000 1000000 -1000000 1000000" << endl;
        return 0;
    }

    long long x, y;
    long long limit = 1000000;

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

    if (seed_val == 1) {

        x = limit;
        y = limit;
    } else if (seed_val == 2) {

        x = -limit;
        y = -limit;
    } else if (seed_val == 3) {

        x = 0;
        y = 0;
    } else if (seed_val == 4) {

        x = -limit;
        y = limit;
    } else if (seed_val == 5) {

        x = limit;
        y = -limit;
    } else if (seed_val > 0 && seed_val <= 10) {

        x = rnd.next(-100, 100);
        y = rnd.next(-100, 100);
    } else {

        if (rnd.next(4) == 0) {
            long long x_edge = rnd.next(limit - 5000, limit) * (rnd.next(2) ? 1 : -1);
            long long y_edge = rnd.next(limit - 5000, limit) * (rnd.next(2) ? 1 : -1);

            int type = rnd.next(3);
            if (type == 0) {
                x = x_edge;
                y = rnd.next(-limit, limit);
            } else if (type == 1) {
                x = rnd.next(-limit, limit);
                y = y_edge;
            } else {
                x = x_edge;
                y = y_edge;
            }
        } else {

            x = rnd.next(-limit, limit);
            y = rnd.next(-limit, limit);
        }
    }

    cout << x << " " << y << endl;

    return 0;
}


The only difference between easy and hard versions is the maximum number of queries. In this version, you are allowed to ask at most $2023$ queries.

This is an interactive problem.

You are playing a game. The circle is divided into $n$ sectors, sectors are numbered from $1$ to $n$ in some order. You are in the adjacent room and do not know either the number of sectors or their numbers. There is also an arrow that initially points to some sector. Initially, the host tells you the number of the sector to which the arrow points. After that, you can ask the host to move the arrow $k$ sectors counterclockwise or clockwise at most $2023$ times. And each time you are told the number of the sector to which the arrow points.

Your task is to determine the integer $n$ — the number of sectors in at most $2023$ queries.

It is guaranteed that $1 \le n \le 10^6$.

Input

The input consists of a single integer $x$ ($1 \le x \le n$) — the number of the initial sector.

Output

After you determine the integer $n$ — the number of sectors, you should output "! n" ($1 \le n \le 10^6$). After that the program should immediately terminate.

Note that, printing the answer does not count as a query.

It is guaranteed that the integer $n$ and the numbers of the sectors are fixed initially and will not be changed by the jury program depending on the queries.

Interaction

After reading the description of the input, you may ask queries. Queries can be of two types:

1. "+ k" ($0 \le k \le 10^9$) — ask to move the arrow $k$ sectors clockwise.
2. "- k" ($0 \le k \le 10^9$) — ask to move the arrow $k$ sectors counterclockwise.

After each query, you should read an integer $x$ ($1 \le x \le n$) — the number of the current sector to which the arrow points.

You are allowed to make at most $2023$ queries in total.

If you make too many queries, you will get Wrong answer.

After printing a query or the answer, do not forget to output a the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:

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

Example

Input

```
1

5

6

7

2

10

9

8

4

3

1
```

Output

```
+ 1

+ 1

+ 1

+ 1

+ 1

+ 1

+ 1

+ 1

+ 1

+ 1

! 10
```

Note

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

using namespace std;

static long long queries = 0;
static const long long query_limit = 2023;
static bool finished = false;

static void log_metrics() {
    if (finished) return;

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

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

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

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

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

    cout << p[start_pos] << endl;

    int current_pos = start_pos;
    long long hard_cap = 20000;

    while (true) {

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

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

        if (token == "!") {
            int ans;
            if (!(cin >> ans)) {
                finish(_pe, "Unexpected EOF reading answer value");
            }
            if (ans == n) {
                finish(_ok, "Correct! n=%d. Queries: %lld", n, queries);
            } else {
                finish(_wa, "Wrong answer. Expected n=%d, found %d", n, ans);
            }
        }

        string op = token;
        if (token == "?") {
            if (!(cin >> op)) {
                finish(_pe, "Unexpected EOF after '?'");
            }
        }

        if (op != "+" && op != "-") {
            finish(_pe, "Invalid query operator: '%s'. Expected '+', '-', or '!'", op.c_str());
        }

        long long k;
        if (!(cin >> k)) {
            finish(_pe, "Unexpected EOF reading k");
        }

        if (k < 0 || k > 1000000000LL) {
            finish(_pe, "k out of range [0, 10^9]: %lld", k);
        }

        queries++;

        if (queries % 10 == 0) {
            tout << "queries=" << queries << endl;
            tout << "query_limit=" << query_limit << endl;
        }

        long long shift = k % n;
        if (op == "+") {
            current_pos = (current_pos + shift) % n;
        } else {

            current_pos = (current_pos - shift + n) % n;
        }

        cout << p[current_pos] << endl;
    }

    return 0;
}

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

using namespace std;

static long long queries = 0;

static long long query_limit = 2023;

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

    }
}

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

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

    registerInteraction(argc, argv);

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

    atexit(log_metrics);

    int n = inf.readInt();

    int start_pos = 0;
    vector<int> p;

    inf.skipBlanks();
    if (!inf.eof()) {

        start_pos = inf.readInt();
        p.resize(n);
        for (int i = 0; i < n; i++) {
            p[i] = inf.readInt();
        }
    } else {

        p = rnd.perm(n, 1);
        start_pos = rnd.next(0, n - 1);
    }

    int curr = start_pos;

    long long hard_cap = 200000;

    cout << p[curr] << endl;

    log_metrics();

    while (true) {

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

        string type;
        if (!(cin >> type)) {
            finish(_pe, "Unexpected end of input from contestant.");
        }

        if (type == "!") {
            int ans;
            if (!(cin >> ans)) {
                finish(_pe, "Expected integer after '!'");
            }

            if (ans == n) {
                finish(_ok, format("Correct! n=%d found in %lld queries.", n, queries));
            } else {
                finish(_wa, format("Wrong answer. Expected n=%d, found %d.", n, ans));
            }
        }
        else if (type == "+" || type == "-") {
            long long k;
            if (!(cin >> k)) {
                finish(_pe, format("Expected integer after '%s'", type.c_str()));
            }

            if (k < 0 || k > 1000000000LL) {
                finish(_pe, format("Argument k=%lld out of range [0, 10^9]", k));
            }

            queries++;

            if (type == "+") {
                curr = (int)((curr + (k % n)) % n);
            } else {
                long long rem = k % n;
                curr = (int)((curr - rem + n) % n);
            }

            cout << p[curr] << endl;

            log_metrics();
        }
        else {
            finish(_pe, format("Unknown query type '%s'", type.c_str()));
        }
    }

    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 seed = (argc > 1) ? atoll(argv[1]) : 0;

    int n;

    if (seed == 1) {
        n = 1;
    } else if (seed == 2) {
        n = 1000000;
    } else if (seed == 3) {
        n = 2023;
    } else if (seed == 4) {
        n = 999983;
    } else {

        int type = rnd.next(1, 100);
        if (type <= 5) {

            n = rnd.next(1, 50);
        } else if (type <= 15) {

            n = rnd.next(1800, 2200);
        } else if (type <= 60) {

            n = rnd.next(500000, 1000000);
        } else {

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

    if (mode == "non") {

        cout << n << "\n";

        int start_pos = rnd.next(0, n - 1);
        cout << start_pos << "\n";

        vector<int> p = rnd.perm(n, 1);
        for (int i = 0; i < n; i++) {
            cout << p[i] << (i == n - 1 ? "" : " ");
        }
        cout << "\n";

    } else {

        cout << n << "\n";
    }

    return 0;
}


This is an interactive problem!

Ehab has a hidden permutation $p$ of length $n$ consisting of the elements from $0$ to $n-1$. You, for some reason, want to figure out the permutation. To do that, you can give Ehab $2$ different indices $i$ and $j$, and he'll reply with $(p_i|p_j)$ where $|$ is the bitwise-or operation.

Ehab has just enough free time to answer $4269$ questions, and while he's OK with answering that many questions, he's too lazy to play your silly games, so he'll fix the permutation beforehand and will not change it depending on your queries. Can you guess the permutation?

Input

The only line contains the integer $n$ $(3 \le n \le 2048)$ — the length of the permutation.

Interaction

To ask a question, print "? $i$ $j$" (without quotes, $i \neq j$) Then, you should read the answer, which will be $(p_i|p_j)$.

If we answer with $-1$ instead of a valid answer, that means you exceeded the number of queries or made an invalid query.

Exit immediately after receiving $-1$ and you will see wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.

To print the answer, print "! $p_1$ $p_2$ $\ldots$ $p_n$" (without quotes). Note that answering doesn't count as one of the $4269$ queries.

After printing a query or printing the answer, do not forget to output end of line and flush the output. Otherwise, you will get idleness limit exceeded. To do this, use:

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

Example

Input

```
3
1
3
2
```

Output

```? 1 2? 1 3? 2 3! 1 0 2
```

Note

In the first sample, the permutation is $[1,0,2]$. You start by asking about $p_1|p_2$ and Ehab replies with $1$. You then ask about $p_1|p_3$ and Ehab replies with $3$. Finally, you ask about $p_2|p_3$ and Ehab replies with $2$. You then guess the permutation.

#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 isIntToken(const string& s) {
    if (s.empty()) return false;
    int i = 0;
    if (s[0] == '-') {
        if ((int)s.size() == 1) return false;
        i = 1;
    }
    for (; i < (int)s.size(); ++i) if (!isdigit((unsigned char)s[i])) return false;
    return true;
}

static bool parseLL(const string& s, long long& out) {
    if (!isIntToken(s)) return false;
    try {
        size_t pos = 0;
        long long v = stoll(s, &pos, 10);
        if (pos != s.size()) return false;
        out = v;
        return true;
    } catch (...) {
        return false;
    }
}

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

    int n = inf.readInt(3, 2048, "n");
    vector<int> p(n);
    for (int i = 0; i < n; ++i) p[i] = inf.readInt(0, n - 1, ("p[" + to_string(i) + "]").c_str());

    query_limit = 4269;

    log_metrics();

    cout << n << endl;

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

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

        if (cmd == "?") {
            string si, sj;
            if (!(cin >> si >> sj)) {
                cout << -1 << endl;
                finish(_pe, "malformed query: expected two indices");
            }

            long long i = -1, j = -1;
            if (!parseLL(si, i) || !parseLL(sj, j)) {
                cout << -1 << endl;
                finish(_pe, "malformed query: indices are not integers");
            }

            if (i < 1 || i > n || j < 1 || j > n || i == j) {
                cout << -1 << endl;
                finish(_pe, "invalid query indices");
            }

            ++queries;
            if (queries > hard_cap) {
                cout << -1 << endl;
                finish(_pe, "hard cap exceeded");
            }

            int ans = (p[(int)i - 1] | p[(int)j - 1]);
            cout << ans << endl;
            continue;
        }

        if (cmd == "!") {
            vector<long long> outp_ll(n);
            for (int i = 0; i < n; ++i) {
                string sx;
                if (!(cin >> sx)) finish(_pe, "malformed answer: not enough numbers");
                long long x = -1;
                if (!parseLL(sx, x)) finish(_pe, "malformed answer: non-integer in permutation");
                outp_ll[i] = x;
            }

            vector<int> outp(n);
            vector<char> seen(n, 0);
            for (int i = 0; i < n; ++i) {
                long long x = outp_ll[i];
                if (x < 0 || x >= n) finish(_wa, "answer contains value out of range");
                if (seen[(int)x]) finish(_wa, "answer contains duplicate values");
                seen[(int)x] = 1;
                outp[i] = (int)x;
            }

            for (int i = 0; i < n; ++i) {
                if (outp[i] != p[i]) finish(_wa, "wrong permutation");
            }
            finish(_ok, "correct");
        }

        finish(_pe, "unknown command token (expected '?' or '!')");
    }
}

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

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

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

    }
}

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

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

static bool readLongLong(long long& x) {
    if (!(cin >> x)) return false;
    return true;
}

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

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

    int n = inf.readInt(3, 2048, "n");

    query_limit = 4269;
    log_metrics();

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

    int k = 0;
    while ((1 << k) <= (n - 1)) ++k;
    int maxMask = (1 << k) - 1;
    if (maxMask < 0) maxMask = 0;

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

    vector<int> feasibleShifts(n);
    iota(feasibleShifts.begin(), feasibleShifts.end(), 0);

    while (true) {
        string cmd;
        if (!readToken(cmd)) {
            finish(_pe, "unexpected EOF from contestant");
        }

        if (cmd == "?") {
            long long iLL, jLL;
            if (!readLongLong(iLL) || !readLongLong(jLL)) {
                finish(_pe, "malformed query: expected two indices");
            }
            if (iLL < 1 || iLL > n || jLL < 1 || jLL > n) {
                finish(_pe, "invalid query: index out of range");
            }
            if (iLL == jLL) {
                finish(_pe, "invalid query: i == j");
            }

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

            int i = int(iLL - 1);
            int j = int(jLL - 1);

            vector<int> cnt(maxMask + 1, 0);
            for (int s : feasibleShifts) {
                int a = i + s;
                if (a >= n) a -= n;
                int b = j + s;
                if (b >= n) b -= n;
                int x = a | b;
                if (x < 0 || x > maxMask) {
                    finish(_pe, "internal error: OR out of expected range");
                }
                cnt[x]++;
            }

            int bestX = 0;
            int bestC = -1;
            for (int x = 0; x <= maxMask; ++x) {
                int c = cnt[x];
                if (c > bestC || (c == bestC && x > bestX)) {
                    bestC = c;
                    bestX = x;
                }
            }
            if (bestC <= 0) {
                finish(_pe, "internal error: no feasible shifts for query");
            }

            vector<int> nextFeasible;
            nextFeasible.reserve(bestC);
            for (int s : feasibleShifts) {
                int a = i + s;
                if (a >= n) a -= n;
                int b = j + s;
                if (b >= n) b -= n;
                if ((a | b) == bestX) nextFeasible.push_back(s);
            }
            if (nextFeasible.empty()) {
                finish(_pe, "internal error: filtering produced empty feasible set");
            }
            feasibleShifts.swap(nextFeasible);

            cout << bestX << "\n";
            cout.flush();
        } else if (cmd == "!") {
            vector<long long> outLL(n);
            for (int idx = 0; idx < n; ++idx) {
                if (!readLongLong(outLL[idx])) {
                    finish(_pe, "malformed answer: expected n integers after '!'");
                }
            }

            vector<int> out(n);
            vector<char> seen(n, 0);
            for (int idx = 0; idx < n; ++idx) {
                long long v = outLL[idx];
                if (v < 0 || v >= n) finish(_pe, "malformed answer: value out of range");
                if (seen[(int)v]) finish(_pe, "malformed answer: duplicate value");
                seen[(int)v] = 1;
                out[idx] = (int)v;
            }

            for (int s : feasibleShifts) {
                bool ok = true;
                for (int pos = 0; pos < n; ++pos) {
                    int expect = pos + s;
                    if (expect >= n) expect -= n;
                    if (out[pos] != expect) {
                        ok = false;
                        break;
                    }
                }
                if (!ok) {
                    finish(_wa, "answer is not correct for all feasible instances");
                }
            }

            finish(_ok, "correct");
        } else {
            finish(_pe, "invalid command token (expected '?' or '!')");
        }
    }
}

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

static bool isPow2(int n) {
    return n > 0 && (n & (n - 1)) == 0;
}

static int popcnt(int x) {
    return __builtin_popcount((unsigned)x);
}

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

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

static vector<int> makePairPermutation(int n, int mask, bool keepPairsAdjacent) {
    vector<char> used(n, 0);
    vector<pair<int,int>> pairs;
    vector<int> leftovers;
    pairs.reserve(n / 2);

    for (int x = 0; x < n; ++x) {
        if (used[x]) continue;
        int y = x ^ mask;
        if (y >= 0 && y < n && y != x && !used[y]) {
            used[x] = used[y] = 1;
            pairs.push_back({x, y});
        } else {
            used[x] = 1;
            leftovers.push_back(x);
        }
    }

    shufflePairs(pairs);
    shuffleVec(leftovers);

    stable_sort(leftovers.begin(), leftovers.end(), [&](int a, int b) {
        int pa = popcnt(a), pb = popcnt(b);
        if (pa != pb) return pa > pb;
        return a < b;
    });

    vector<int> p;
    p.reserve(n);

    if (keepPairsAdjacent) {
        for (auto [a, b] : pairs) {
            if (rnd.next(0, 1) == 0) {
                p.push_back(a);
                p.push_back(b);
            } else {
                p.push_back(b);
                p.push_back(a);
            }
        }
        for (int x : leftovers) p.push_back(x);
    } else {
        vector<int> pool;
        pool.reserve(n);
        for (auto [a, b] : pairs) {
            if (rnd.next(0, 1) == 0) {
                pool.push_back(a);
                pool.push_back(b);
            } else {
                pool.push_back(b);
                pool.push_back(a);
            }
        }
        for (int x : leftovers) pool.push_back(x);
        shuffleVec(pool);
        p.swap(pool);
    }

    if ((int)p.size() != n) {

        p.clear();
        for (int i = 0; i < n; ++i) p.push_back(i);
        shuffleVec(p);
    }
    return p;
}

static vector<int> makeBitReversalPermutation(int n) {
    int k = 0;
    while ((1 << k) < n) ++k;
    int mask = n - 1;
    int xorMask = rnd.next(0, mask);
    int shift = rnd.next(0, n - 1);

    vector<int> p(n);
    for (int i = 0; i < n; ++i) {
        int x = i;
        int r = 0;
        for (int b = 0; b < k; ++b) {
            r = (r << 1) | (x & 1);
            x >>= 1;
        }
        r ^= xorMask;
        p[(i + shift) & mask] = r;
    }
    return p;
}

static vector<int> makeGrayPermutation(int n) {
    int mask = n - 1;
    int xorMask = rnd.next(0, mask);
    int shift = rnd.next(0, n - 1);

    vector<int> p(n);
    for (int i = 0; i < n; ++i) {
        int g = i ^ (i >> 1);
        g ^= xorMask;
        p[(i + shift) & mask] = g;
    }
    return p;
}

static vector<int> makeRandomPermutation(int n) {
    vector<int> p(n);
    iota(p.begin(), p.end(), 0);
    shuffleVec(p);
    return p;
}

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

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

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

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

        seed = atoll(argv[1]);
    }

    int n = 0;
    if (seed == 1) {
        n = 3;
    } else if (seed == 2) {
        n = 2048;
    } else if (seed == 3) {
        n = 2047;
    } else if (nOpt >= 3) {
        n = nOpt;
    } else {

        n = (seed % 17 == 0 ? 2047 : 2048);
    }

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

    if (mode == "adp") {

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

    cout << n << "\n";

    vector<int> p;
    if (seed == 1) {
        p = {1, 0, 2};
        printPermutation(p);
        return 0;
    }
    if (seed == 2) {
        p.reserve(n);
        for (int x = 0; x < n / 2; ++x) {
            p.push_back(x);
            p.push_back((n - 1) - x);
        }
        printPermutation(p);
        return 0;
    }
    if (seed == 3) {
        int mask = (1 << 11) - 1;
        p.reserve(n);
        p.push_back(0);
        for (int x = 1; x <= 1023; ++x) {
            int y = x ^ mask;
            p.push_back(x);
            p.push_back(y);
        }
        printPermutation(p);
        return 0;
    }

    if (pattern == "auto") {
        if (isPow2(n)) {
            int t = (int)(seed % 3);
            if (t == 0) pattern = "pair";
            else if (t == 1) pattern = "rev";
            else pattern = "gray";
        } else {
            pattern = "pair";
        }
    }

    if (pattern == "pair") {
        int k = 0;
        while ((1 << k) < n) ++k;
        int mask = (1 << k) - 1;
        bool keepAdjacent = true;
        p = makePairPermutation(n, mask, keepAdjacent);
    } else if (pattern == "rev") {
        if (isPow2(n)) p = makeBitReversalPermutation(n);
        else p = makeRandomPermutation(n);
    } else if (pattern == "gray") {
        if (isPow2(n)) p = makeGrayPermutation(n);
        else p = makeRandomPermutation(n);
    } else if (pattern == "rand") {
        p = makeRandomPermutation(n);
    } else {

        int k = 0;
        while ((1 << k) < n) ++k;
        int mask = (1 << k) - 1;
        p = makePairPermutation(n, mask, true);
    }

    printPermutation(p);
    return 0;
}


This is an interactive problem.

You are given a grid with $n$ rows and $m$ columns. The coordinates $(x, y)$ represent the cell on the grid, where $x$ ($1 \leq x \leq n$) is the row number counting from the top and $y$ ($1 \leq y \leq m$) is the column number counting from the left. It is guaranteed that there are exactly $2$ mines in the grid at distinct cells, denoted as $(x_1, y_1)$ and $(x_2, y_2)$. You are allowed to make no more than $4$ queries to the interactor, and after these queries, you need to provide the location of one of the mines.

In each query, you can choose any grid cell $(x, y)$, and in return, you will receive the minimum Manhattan distance from both the mines to the chosen cell, i.e., you will receive the value $\min(|x-x_1|+|y-y_1|, |x-x_2|+|y-y_2|)$.

Your task is to determine the location of one of the mines after making the queries.

Input

Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \leq t \leq 3 \cdot 10^{3}$) — the number of test cases.

The only line of each test case contains two integers $n$ and $m$ ($2 \leq n \leq 10^{8}$, $2 \leq m \leq 10^{8}$) — the number of rows and columns.

Interaction

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

Then you are allowed to make at most $4$ queries in the following way:

"? x y" ($1 \leq x \leq n$ and $1 \leq y \leq m$)

After each one, you should read an integer $d$ which is equal to $\min(|x-x_1|+|y-y_1|, |x-x_2|+|y-y_2|)$.

When you have found the location of any one of the mines, print a single line "! x y" (without quotes), representing the row and the column of one of the mines. Outputting the answer does not count as a query.

After printing the answer, your program must then continue to solve the remaining test cases, or exit if all test cases have been solved.

The interactor for this problem is not adaptive: cells of mines are fixed before any queries are made.

After printing a query, do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:

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

Example

Input

```
2
4 4

3

2

2

0

5 5

1

2

3
```

Output

```
? 1 1

? 1 4

? 4 1

? 2 3

! 2 3

? 5 5

? 2 2

? 3 3

! 1 1
```

Note

In the first test case, we start by querying the upper-left corner $(1, 1)$ and get the result $3$, which means that there is a mine on the counter diagonal, and there is no mine above it.

In the image below, each cell contains a number indicating the distance to the blue cell. The green cells are candidates to contain the nearest mine.

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

Then we ask three cells on that diagonal, and at the last query, we get the result $0$, which means that a mine is found at the position $(2, 3)$.

The second mine was located at the position $(3, 2)$.

In the second test case, we start by asking the lower-right corner $(5, 5)$, and get the result $1$, which means that one of the two neighbours contains a mine, let's call it mine $1$.

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

Then we ask cell $(2, 2)$. We can see that these green cells don't intersect with the green cells from the first query, so they contain the other mine, let's call it mine $2$.

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

Query $3$ is cell $(3, 3)$. These cells contain mine $1$, but we still don't know where exactly. Nevertheless, we can determine that the only possible cell for mine $2$ is $(1, 1)$, because all other candidates are at a distance closer than $3$ for this query.

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

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

long long dist(long long r1, long long c1, long long r2, long long c2) {
    return std::abs(r1 - r2) + std::abs(c1 - c2);
}

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

    registerInteraction(argc, argv);

    atexit(log_metrics);

    int t = inf.readInt();

    query_limit = 4LL * t;

    log_metrics();

    cout << t << endl;

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

        int n = inf.readInt();
        int m = inf.readInt();
        int x1 = inf.readInt();
        int y1 = inf.readInt();
        int x2 = inf.readInt();
        int y2 = inf.readInt();

        cout << n << " " << m << endl;

        while (true) {

            if (queries > max(200000LL, 10 * query_limit)) {
                finish(_pe, "Hard query limit exceeded (infinite loop?)");
            }

            string token;
            if (!(cin >> token)) {
                finish(_wa, "Unexpected end of output (expected query or answer)");
            }

            if (token == "!") {

                int ax, ay;
                if (!(cin >> ax >> ay)) {
                    finish(_wa, "Cannot read answer coordinates");
                }

                bool match1 = (ax == x1 && ay == y1);
                bool match2 = (ax == x2 && ay == y2);

                if (match1 || match2) {

                    break;
                } else {
                    finish(_wa, format("Incorrect answer (%d, %d). Mines are at (%d, %d) and (%d, %d).",
                                       ax, ay, x1, y1, x2, y2));
                }
            } else {

                int qx, qy;

                if (token == "?") {
                    if (!(cin >> qx >> qy)) {
                        finish(_wa, "Cannot read query coordinates after '?'");
                    }
                } else {

                    try {
                        qx = stoi(token);
                    } catch (...) {
                        finish(_wa, format("Invalid token '%s' (expected '?', '!', or integer)", token.c_str()));
                    }
                    if (!(cin >> qy)) {
                        finish(_wa, "Cannot read y-coordinate");
                    }
                }

                queries++;

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

                if (qx < 1 || qx > n || qy < 1 || qy > m) {
                    finish(_wa, format("Query (%d, %d) is out of bounds for grid %d x %d", qx, qy, n, m));
                }

                long long d1 = dist(qx, qy, x1, y1);
                long long d2 = dist(qx, qy, x2, y2);
                long long ans = min(d1, d2);

                cout << ans << endl;
            }
        }
    }

    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 seed_val = atoi(argv[1]);

    int t = opt<int>("t", 50);
    if (seed_val <= 5) t = 20;

    println(t);

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

        if (seed_val == 1) {

            n = rnd.next(2, 8);
            m = rnd.next(2, 8);
        } else if (seed_val == 2) {

            if (rnd.next(2)) {
                n = rnd.next(2, 10);
                m = rnd.next(10000, 100000000);
            } else {
                n = rnd.next(10000, 100000000);
                m = rnd.next(2, 10);
            }
        } else if (seed_val == 3) {

            n = rnd.next(10000000, 100000000);
            m = rnd.next(10000000, 100000000);
        } else {

            int p = rnd.next(100);
            if (p < 20) {

                n = rnd.next(2, 20);
                m = rnd.next(2, 20);
            } else if (p < 50) {

                if (rnd.next(2)) {
                    n = rnd.next(2, 50);
                    m = rnd.next(1000, 100000000);
                } else {
                    n = rnd.next(1000, 100000000);
                    m = rnd.next(2, 50);
                }
            } else {

                n = rnd.next(1000, 100000000);
                m = rnd.next(1000, 100000000);
            }
        }

        if (mode == "adp") {

            println(n, m);
        } else {

            int x1, y1, x2, y2;
            bool fixed_pattern = false;

            if (seed_val <= 3 && i < 2) {
                if (i == 0) {

                    x1 = 1; y1 = 1;
                    x2 = n; y2 = m;
                    fixed_pattern = true;
                } else if (i == 1) {

                    x1 = 1; y1 = m;
                    x2 = n; y2 = 1;
                    fixed_pattern = true;
                }
            }

            if (!fixed_pattern) {

                if (rnd.next(100) < 30) {
                    x1 = rnd.next(1, n);
                    y1 = rnd.next(1, m);

                    int dx = rnd.next(-2, 2);
                    int dy = rnd.next(-2, 2);
                    x2 = clamp(x1 + dx, 1, n);
                    y2 = clamp(y1 + dy, 1, m);

                    if (x1 == x2 && y1 == y2) {
                        if (x2 < n) x2++; else x2--;
                    }
                } else {

                    x1 = rnd.next(1, n);
                    y1 = rnd.next(1, m);
                    do {
                        x2 = rnd.next(1, n);
                        y2 = rnd.next(1, m);
                    } while (x1 == x2 && y1 == y2);
                }
            }
            println(n, m, x1, y1, x2, y2);
        }
    }

    return 0;
}


C. Interactive Bulls and Cows (Hard)

The only difference from the previous problem is the constraint on the number of requests. In this problem your program should guess the answer doing at most 7 requests.

This problem is a little bit unusual. Here you are to implement an interaction with a testing system. That means that you can make queries and get responses in the online mode. Please be sure to use the stream flushing operation after each query's output in order not to leave part of your output in some buffer. For example, in C++ you've got to use the fflush(stdout) function, in Java — call System.out.flush(), and in Pascal — flush(output).

Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking paper and pencil game for two players, predating the similar commercially marketed board game Mastermind.

On a sheet of paper, the first player thinks a secret string. This string consists only of digits and has the length 4. The digits in the string must be all different, no two or more equal digits are allowed.

Then the second player tries to guess his opponent's string. For every guess the first player gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows". Thus a response is a pair of numbers — the number of "bulls" and the number of "cows". A try can contain equal digits.

More formally, let's the secret string is *s* and the second player are trying to guess it with a string *x*. The number of "bulls" is a number of such positions *i* (1 ≤ *i* ≤ 4) where *s*[*i*] = *x*[*i*]. The number of "cows" is a number of such digits *c* that *s* contains *c* in the position *i* (i.e. *s*[*i*] = *c*), *x* contains *c*, but *x*[*i*] ≠ *c*.

For example, the secret string is "0427", the opponent's try is "0724", then the answer is 2 bulls and 2 cows (the bulls are "0" and "2", the cows are "4" and "7"). If the secret string is "0123", the opponent's try is "0330", then the answer is 1 bull and 1 cow.

In this problem you are to guess the string *s* that the system has chosen. You only know that the chosen string consists of 4 distinct digits.

You can make queries to the testing system, each query is the output of a single 4-digit string. The answer to the query is the number of bulls and number of cows. If the system's response equals "4 0", that means the interaction with your problem is over and the program must terminate. That is possible for two reasons — the program either guessed the number *x* or made an invalid action (for example, printed letters instead of digits).

Your program is allowed to do at most 7 queries.

Input

To read answers to the queries, the program must use the standard input.

The program will receive pairs of non-negative integers in the input, one pair per line. The first number in a pair is a number of bulls and the second one is a number of cows of the string *s* and the string *x**i* printed by your program. If the system response equals "4 0", then your solution should terminate.

The testing system will let your program read the *i*-th pair of integers from the input only after your program displays the corresponding system query in the output: prints value *x**i* in a single line and executes operation flush.

Output

The program must use the standard output to print queries.

Your program must output requests — 4-digit strings *x*1, *x*2, ..., one per line. After the output of each line the program must execute flush operation. The program should read the answer to the query from the standard input.

Your program is allowed to do at most 7 queries.

Examples

Input

```
0 1
2 0
1 1
0 4
2 1
4 0
```

Output

```
8000
0179
3159
3210
0112
0123
```

Note

The secret string *s* in the example is "0123".

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

using namespace std;

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

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

    }
}

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

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

    string secret = inf.readToken();

    if (secret.length() != 4) {
        finish(_fail, "Hidden input (secret) length is not 4. Got: '%s'", secret.c_str());
    }
    {
        set<char> distinct;
        for (char c : secret) {
            if (!isdigit(c)) finish(_fail, "Hidden input contains non-digits");
            distinct.insert(c);
        }
        if (distinct.size() != 4) {
            finish(_fail, "Hidden input digits must be distinct");
        }
    }

    log_metrics();

    int hard_cap = 200;

    while (true) {

        string token;
        if (!(cin >> token)) {
            finish(_wa, "Unexpected EOF: solution terminated without correct guess");
        }

        if (token == "?" || token == "!") {
            if (!(cin >> token)) {
                finish(_wa, "Unexpected EOF after protocol prefix");
            }
        } else if (token.length() > 0 && (token[0] == '?' || token[0] == '!')) {

            token = token.substr(1);
        }

        if (token.length() != 4) {
            finish(_pe, "Query must be a 4-digit string. Got length %d: '%s'", (int)token.length(), token.c_str());
        }
        for (char c : token) {
            if (!isdigit(c)) {
                finish(_pe, "Query must contain only digits. Got: '%s'", token.c_str());
            }
        }

        queries++;

        int bulls = 0;
        int cows = 0;

        for (int i = 0; i < 4; ++i) {
            char s_char = secret[i];
            char x_char = token[i];

            if (s_char == x_char) {
                bulls++;
            } else {

                bool found = false;
                for (int j = 0; j < 4; ++j) {
                    if (token[j] == s_char) {
                        found = true;
                        break;
                    }
                }
                if (found) cows++;
            }
        }

        cout << bulls << " " << cows << endl;

        log_metrics();

        if (bulls == 4) {
            finish(_ok, "Guessed correctly in %lld queries", queries);
        }

        if (queries >= hard_cap) {
            finish(_pe, "Hard query limit exceeded (>%d)", hard_cap);
        }
    }

    return 0;
}

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

using namespace std;

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

static string secret_fixed;

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

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

pair<int, int> calc_bulls_cows(const string& s, const string& g) {
    int bulls = 0;
    int count_s[10] = {0};
    int count_g[10] = {0};

    for (int i = 0; i < 4; ++i) {
        if (s[i] == g[i]) {
            bulls++;
        }
        count_s[s[i] - '0']++;
        count_g[g[i] - '0']++;
    }

    int common = 0;
    for (int i = 0; i < 10; ++i) {
        common += min(count_s[i], count_g[i]);
    }

    int cows = common - bulls;
    return {bulls, cows};
}

bool is_valid_guess(const string& s) {
    if (s.length() != 4) return false;
    for (char c : s) {
        if (!isdigit(c)) return false;
    }
    return true;
}

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

    atexit(log_metrics);

    string token = inf.readToken();
    if ((int)token.size() == 4) {
        secret_fixed = token;
    } else {
        long long seed_val = 0;
        try {
            seed_val = stoll(token);
        } catch (...) {
            finish(_fail, "Invalid seed in hidden input");
        }
        mt19937 rng((uint32_t)seed_val);
        vector<int> digs(10);
        iota(digs.begin(), digs.end(), 0);
        shuffle(digs.begin(), digs.end(), rng);
        secret_fixed.clear();
        for (int i = 0; i < 4; i++) secret_fixed.push_back(char('0' + digs[i]));
    }

    if (!is_valid_guess(secret_fixed)) finish(_fail, "Secret is not 4 digits");
    {
        bool used[10] = {0};
        for (char c : secret_fixed) {
            int d = c - '0';
            if (used[d]) finish(_fail, "Secret digits not distinct");
            used[d] = true;
        }
    }

    log_metrics();

    while (true) {

        string guess;
        if (!(cin >> guess)) {
            finish(_wa, "Unexpected EOF: solution terminated without correct guess");
        }

        if (guess == "?" || guess == "!") {
            if (!(cin >> guess)) finish(_pe, "Unexpected EOF after protocol prefix");
        } else if (!guess.empty() && (guess[0] == '?' || guess[0] == '!')) {
            guess = guess.substr(1);
        }

        if (!is_valid_guess(guess)) {
            finish(_pe, "Invalid query format");
        }

        queries++;
        log_metrics();

        if (queries > 200) {
            finish(_pe, "Too many queries (hard cap)");
        }

        pair<int, int> response = calc_bulls_cows(secret_fixed, guess);

        cout << response.first << " " << response.second << endl;

        if (response.first == 4 && response.second == 0) {
            finish(_ok, "Guessed " + guess);
        }
    }

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

    if (mode == "adp") {

        cout << rnd.next(100000000, 999999999) << endl;
    } else {

        long long seed_val = 0;
        try {
            if (argc > 1) seed_val = stoll(argv[1]);
        } catch (...) {
            seed_val = 0;
        }

        if (seed_val == 1) {

            cout << "0123" << endl;
        } else if (seed_val == 2) {

            cout << "9876" << endl;
        } else if (seed_val == 3) {

            cout << "1209" << endl;
        } else {

            vector<int> p(10);
            iota(p.begin(), p.end(), 0);
            shuffle(p.begin(), p.end());

            for (int i = 0; i < 4; ++i) {
                cout << p[i];
            }
            cout << endl;
        }
    }

    return 0;
}


This is an interactive problem.

There is an array of $n$ cells, numbered from 1 to $n$ . For each pair of integers $( i , j )$ , where $1 \leq i \leq j \leq n$ , there is a barrier covering all cells from $i$ to $j$ , inclusive. Each barrier is either active or inactive. A cell is visible if there are no active barriers that cover it. Otherwise, the cell is invisible.

The state of each barrier is unknown to you. All you can observe is the number of visible cells. But you can flip the state of any barrier: if it’s active, it turns inactive, and the other way around. Your task is to make all barriers inactive, so that all cells become visible.

# Interaction Protocol

First, read an integer $n$ , denoting the number of cells ( $1 \leq n \leq 1 0$ ).

The following interaction will proceed in rounds. Your program should start each round by reading an integer $k$ , denoting the number of currently visible cells $0 \leq k \leq n$ ).

• If $k = n$ , then the task is done and your program must exit.
• If $k < n$ , you can flip the state of any barrier. On a separate line, print two integers $i$ and $j$ to flip the state of the $( i , j )$ barrier $1 \leq i \leq j \leq n$ ). After your query, the next round begins, and your program should read a new value of $k$ .

Your solution must make all cells visible using at most 2500 flips. In the beginning, not all cells are visible ( $k < n$ in the first round).

The interactor is not adaptive: in every test, the state of all barriers is chosen before the program execution.

# Example

standard input	standard output	Initial state

3

0	22

0	23

1	12

2		1 2 3

3	22

# Note

In the example, initially, only two barriers, $( 1 , 2 )$ and $( 2 , 3 )$ , are active. These two barriers cover all three cells, so $k$ is equal to $0$ in the first round.

• After flipping the $( 2 , 2 )$ barrier, there are now three active barriers, and still $k = 0$ visible cells.
• After flipping the $( 1 , 2 )$ barrier, cell 1 becomes visible, so now there is $k = 1$ visible cell.
• After flipping the $( 2 , 3 )$ barrier, cell 3 also becomes visible. The only invisible cell now is 2, covered by the only active barrier, $( 2 , 2 )$ , and there are $k = 2$ visible cells.
• After flipping the $( 2 , 2 )$ barrier, all barriers are now inactive, and all cells are visible. After reading $k = 3$ , the program terminates.

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

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

int n;
bool active[15][15];

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 count_visible() {
    int visible = 0;
    for (int c = 1; c <= n; c++) {
        bool covered = false;

        for (int i = 1; i <= n; i++) {
            for (int j = i; j <= n; j++) {
                if (active[i][j]) {
                    if (c >= i && c <= j) {
                        covered = true;
                        break;
                    }
                }
            }
            if (covered) break;
        }
        if (!covered) visible++;
    }
    return visible;
}

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

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

    n = inf.readInt(1, 10, "n");
    int m = inf.readInt(0, n * n, "m");

    memset(active, 0, sizeof(active));
    for (int k = 0; k < m; k++) {
        int u = inf.readInt(1, n, "u");

        int v = inf.readInt(u, n, "v");
        active[u][v] = true;
    }

    query_limit = 2500;
    log_metrics();

    cout << n << endl;

    while (true) {

        int k = count_visible();
        cout << k << endl;

        if (k == n) {
            finish(_ok, "All cells are visible.");
        }

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

        if (queries % 20 == 0) {
            log_metrics();
        }

        string token;
        if (!(cin >> token)) {
            finish(_wa, "Unexpected EOF waiting for query.");
        }

        int u, v;
        if (token == "?") {
            if (!(cin >> u >> v)) {
                finish(_wa, "Incomplete query parameters after '?'.");
            }
        } else if (token == "!") {

            finish(_wa, "Protocol violation: unexpected token '!'.");
            return 0;
        } else {

            try {
                u = stoi(token);
            } catch (...) {
                finish(_wa, "Invalid query format: expected integer.");
                return 0;
            }
            if (!(cin >> v)) {
                finish(_wa, "Incomplete query: expected second integer.");
            }
        }

        if (u < 1 || u > n || v < 1 || v > n || u > v) {
            finish(_wa, format("Invalid barrier coordinates: %d %d (must be 1 <= i <= j <= n)", u, v));
        }

        active[u][v] = !active[u][v];
        queries++;
    }

    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) {

        if (rnd.next(5) == 0) {
            n = rnd.next(1, 9);
        } else {
            n = 10;
        }
    }

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

    vector<pair<int, int>> all_barriers;
    for (int i = 1; i <= n; ++i) {
        for (int j = i; j <= n; ++j) {
            all_barriers.push_back({i, j});
        }
    }

    vector<pair<int, int>> active;
    int type = rnd.next(100);

    if (type < 5) {

        active = all_barriers;
    } else if (type < 15) {

        active.push_back(all_barriers[rnd.next(all_barriers.size())]);
    } else if (type < 25) {

        vector<pair<int, int>> cands;
        for (auto p : all_barriers) {
            if (p.first == p.second) cands.push_back(p);
        }
        for (auto p : cands) {
            if (rnd.next(2)) active.push_back(p);
        }
    } else if (type < 35) {

        vector<pair<int, int>> cands;
        for (auto p : all_barriers) {
            if (p.second - p.first + 1 > n / 2) cands.push_back(p);
        }
        if (cands.empty()) cands = all_barriers;
        for (auto p : cands) {
            if (rnd.next(2)) active.push_back(p);
        }
    } else if (type < 70) {

        for (auto p : all_barriers) {
            if (rnd.next(2)) active.push_back(p);
        }
    } else {

        for (auto p : all_barriers) {
            if (rnd.next(100) < 20) active.push_back(p);
        }
    }

    if (active.empty()) {
        active.push_back(all_barriers[rnd.next(all_barriers.size())]);
    }

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

    cout << n << endl;
    cout << active.size() << endl;
    for (auto p : active) {
        cout << p.first << " " << p.second << endl;
    }

    return 0;
}


Technically, this is an interactive problem.

An array $a$ of $m$ numbers is called divisible if at least one of the following conditions holds:

* There exists an index $i$ ($1 \le i < m$) and an integer $x$ such that for all indices $j$ ($j \le i$), it holds that $a_{j} \le x$ and for all indices $k$ ($k > i$), it holds that $a_{k} > x$.
* There exists an index $i$ ($1 \le i < m$) and an integer $x$ such that for all indices $j$ ($j \le i$), it holds that $a_{j} > x$ and for all indices $k$ ($k > i$), it holds that $a_{k} \le x$.

You are given a permutation $p$ of integers $1, 2, \dots, n$. Your task is to answer queries of the following form fast: if we take only the segment [$l$, $r$] from the permutation, that is, the numbers $p_{l}, p_{l + 1}, \dots, p_{r}$, is this subarray of numbers divisible?

Queries will be submitted in interactive mode in groups of $10$, meaning you will not receive the next group of queries until you output all answers for the current group.

Input

The first line contains one integer $n$ ($2 \le n \le 2 \cdot 10^{5}$) — the size of the permutation.

The second line contains $n$ integers $p_{i}$ ($1 \le p_{i} \le n$) — the permutation of natural numbers itself.

The third line contains one integer $q$ ($10 \le q \le 10^{6}, q \bmod 10 = 0$) — the number of queries.

The following $q$ lines contain two integers $l$ and $r$ ($1 \le l < r \le n$) — the parameters of the query.

Output

For each query, output the string "YES" if the subarray from this query is divisible and "NO" otherwise.

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

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

You have to flush the output buffer after the $10$-th, $20$-th, $30$-th query (and so on), i. e. after each query with index divisible by $10$. After that, you can read the next group of queries.

Example

Input

```
7

4 2 3 6 1 5 7

20

1 2

1 3

1 4

1 5

1 6

2 3

2 4

2 5

2 6

3 4

3 5

3 6

4 5

4 6

5 6

1 7

2 7

3 7

4 7

5 7
```

Output

```
YES
YES
YES
YES
NO
YES
YES
YES
NO
YES
YES
NO
YES
YES
YES
YES
YES
YES
YES
YES
```

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

static long long queries_processed = 0;
static long long total_queries = 0;

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

    }
}

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

const int MAXN = 200005;
const int LOGN = 19;
int st_min[MAXN][LOGN];
int st_max[MAXN][LOGN];
int st_min_idx[MAXN][LOGN];
int st_max_idx[MAXN][LOGN];
int lg[MAXN];
int n;
vector<int> p;

void build_sparse() {
    lg[1] = 0;
    for (int i = 2; i <= n; i++) lg[i] = lg[i/2] + 1;

    for (int i = 1; i <= n; i++) {
        st_min[i][0] = p[i-1];
        st_max[i][0] = p[i-1];
        st_min_idx[i][0] = i;
        st_max_idx[i][0] = i;
    }

    for (int j = 1; j < LOGN; j++) {
        for (int i = 1; i + (1 << j) - 1 <= n; i++) {

            st_min[i][j] = min(st_min[i][j-1], st_min[i + (1 << (j-1))][j-1]);
            st_max[i][j] = max(st_max[i][j-1], st_max[i + (1 << (j-1))][j-1]);

            int idx1 = st_min_idx[i][j-1];
            int idx2 = st_min_idx[i + (1 << (j-1))][j-1];
            st_min_idx[i][j] = (p[idx1-1] < p[idx2-1]) ? idx1 : idx2;

            idx1 = st_max_idx[i][j-1];
            idx2 = st_max_idx[i + (1 << (j-1))][j-1];
            st_max_idx[i][j] = (p[idx1-1] > p[idx2-1]) ? idx1 : idx2;
        }
    }
}

int query_min(int l, int r) {
    if (l > r) return 1e9;
    int j = lg[r - l + 1];
    return min(st_min[l][j], st_min[r - (1 << j) + 1][j]);
}

int query_max(int l, int r) {
    if (l > r) return -1e9;
    int j = lg[r - l + 1];
    return max(st_max[l][j], st_max[r - (1 << j) + 1][j]);
}

int query_min_idx(int l, int r) {
    int j = lg[r - l + 1];
    int idx1 = st_min_idx[l][j];
    int idx2 = st_min_idx[r - (1 << j) + 1][j];
    return (p[idx1-1] < p[idx2-1]) ? idx1 : idx2;
}

int query_max_idx(int l, int r) {
    int j = lg[r - l + 1];
    int idx1 = st_max_idx[l][j];
    int idx2 = st_max_idx[r - (1 << j) + 1][j];
    return (p[idx1-1] > p[idx2-1]) ? idx1 : idx2;
}

bool check_type1(int l, int r) {
    int m = query_min_idx(l, r);
    if (m == r) return false;

    int curr = m;
    int M = query_max(l, curr);

    while (curr < r) {

        int low = curr, high = r - 1;
        int k = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (query_min(mid + 1, r) > M) {
                k = mid;
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }

        if (k == -1) return false;

        int new_M = query_max(l, k);

        if (new_M < query_min(k + 1, r)) return true;

        M = new_M;
        curr = k;
    }
    return false;
}

bool check_type2(int l, int r) {
    int m = query_max_idx(l, r);
    if (m == r) return false;

    int curr = m;
    int MN = query_min(l, curr);

    while (curr < r) {

        int low = curr, high = r - 1;
        int k = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (query_max(mid + 1, r) < MN) {
                k = mid;
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }

        if (k == -1) return false;

        int new_MN = query_min(l, k);
        if (new_MN > query_max(k + 1, r)) return true;

        MN = new_MN;
        curr = k;
    }
    return false;
}

bool solve(int l, int r) {
    if (l >= r) return false;
    return check_type1(l, r) || check_type2(l, r);
}

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

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

    n = inf.readInt(2, 200000, "n");
    p.resize(n);
    for (int i = 0; i < n; i++) {
        p[i] = inf.readInt(1, n, "p_i");
    }
    int q = inf.readInt(10, 1000000, "q");
    total_queries = q;

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

    build_sparse();

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

    int group_size = 10;
    for (int i = 0; i < q; i += group_size) {
        int current_group_end = min(q, i + group_size);
        int current_group_count = current_group_end - i;

        for (int j = i; j < current_group_end; j++) {
            cout << all_queries[j].l << " " << all_queries[j].r << "\n";
        }
        cout.flush();

        for (int j = i; j < current_group_end; j++) {
            string token = ouf.readToken("YES|NO");
            bool ans = (token == "YES");

            bool expected = solve(all_queries[j].l, all_queries[j].r);

            if (ans != expected) {
                finish(_wa, format("Wrong answer for query %d (Expected %s, Got %s)",
                                   j + 1, expected ? "YES" : "NO", token.c_str()));
            }
            queries_processed++;
        }
    }

    finish(_ok, "All queries answered correctly");
}

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

using namespace std;

vector<int> get_permutation(int n, int type) {
    vector<int> p(n);
    if (type == 0) {
        iota(p.begin(), p.end(), 1);
        shuffle(p.begin(), p.end());
    } else if (type == 1) {
        iota(p.begin(), p.end(), 1);
    } else if (type == 2) {
        iota(p.begin(), p.end(), 1);
        reverse(p.begin(), p.end());
    } else if (type == 3) {

        vector<int> left, right;
        for (int i = 1; i <= n; i++) {
            if (rnd.next(2)) left.push_back(i);
            else right.push_back(i);
        }
        sort(left.rbegin(), left.rend());
        sort(right.begin(), right.end());
        int idx = 0;
        for (int x : left) p[idx++] = x;
        for (int x : right) p[idx++] = x;
    } else {

        int L = 1, R = n;
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) p[i] = L++;
            else p[i] = R--;
        }

        if (rnd.next(2)) {
            for(int &x : p) x = n - x + 1;
        }
    }
    return p;
}

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

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

    int seed = atoi(argv[1]);

    int n;
    if (n_arg != -1) n = n_arg;
    else {

        if (seed <= 5) n = rnd.next(10, 100);
        else n = rnd.next(100000, 200000);
    }

    int q;
    if (q_arg != -1) q = q_arg;
    else {
        if (seed <= 5) q = rnd.next(1, 10) * 10;
        else q = rnd.next(50000, 100000) * 10;
    }

    q = (q / 10) * 10;
    if (q < 10) q = 10;

    if (q > 1000000) q = 1000000;

    int type = 0;
    if (mode == "adp") {

        type = rnd.next(3, 4);
    } else {

        if (seed == 1) type = 1;
        else if (seed == 2) type = 2;
        else if (seed == 3) type = 3;
        else type = 0;

        if (seed > 10 && rnd.next(5) == 0) type = rnd.next(1, 4);
    }

    vector<int> p = get_permutation(n, type);

    cout << n << endl;

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

    cout << q << endl;

    for (int i = 0; i < q; i++) {
        int l, r;
        int s = rnd.next(100);

        if (s < 20) {

            int max_len = min(n, 20);
            int len = rnd.next(2, max_len);
            l = rnd.next(1, n - len + 1);
            r = l + len - 1;
        } else if (s < 50) {

            int min_len = min(n, 10);
            int max_len = min(n, (int)sqrt(n) + 100);

            if (min_len > max_len) swap(min_len, max_len);

            int len = rnd.next(min_len, max_len);
            l = rnd.next(1, n - len + 1);
            r = l + len - 1;
        } else if (s < 80) {

            l = rnd.next(1, n / 2);
            r = rnd.next(n / 2 + 1, n);
        } else {

            int margin = max(1, n / 20);
            l = rnd.next(1, margin);
            r = rnd.next(n - margin + 1, n);

            if (l >= r) { l = 1; r = n; }
        }
        cout << l << " " << r << "\n";
    }

    return 0;
}