Problem: cf1438_f
Difficulty: easy
Categories: graph, math
Time limit: 4000 ms, memory limit: 256 MB

This is an interactive problem.

Igor wants to find the key to Olha's heart. The problem is, that it's at the root of a binary tree.

There is a perfect binary tree of height $h$ consisting of $n = 2^{h} - 1$ nodes. The nodes have been assigned distinct labels from $1$ to $n$. However, Igor only knows $h$ and does not know which label corresponds to which node.

To find key to Olha's heart he needs to find the label assigned to the root by making queries of the following type at most $n+420$ times:

* Select three distinct labels $u$, $v$ and $w$ ($1 \leq u,v,w \leq n$).
* In response, Olha (the grader) will tell him the label of the lowest common ancestor of nodes labelled $u$ and $v$, if the tree was rooted at the node labelled $w$ instead.

Help Igor to find the root!

Note: the grader is not adaptive: the labels are fixed before any queries are made.

Input

The first and only line contains a single integer $h$ ($3 \le h \le 18$) — the height of the tree.

Interaction

You begin the interaction by reading $h$.

To make a query for labels $u, v, w$, in a separate line output "? u v w".

Numbers in the query have to satisfy $1 \le u, v, w \le n$. Additionally, $u \ne v$, $u \ne w$, and $v \ne w$.

In response, you will receive $1 \le x \le n$, the label of the lowest common ancestor of $u$ and $v$, if the tree was rooted at $w$.

In case your query is invalid or you asked more than $n+420$ queries, program will print $-1$ and will finish interaction. You will receive Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.

When you determine the label assigned to the root, output "! r", where $r$ is the label of the root.

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

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

Example

Input

```
3

2

7

4
```

Output

```
? 7 3 5

? 1 6 4

? 1 5 4

! 4
```

Note

The labels corresponding to the tree in the example are [$4$,$7$,$2$,$6$,$1$,$5$,$3$], meaning the root is labelled $4$, and for $1 < i \le n$, the parent of $p_i$ is $p_{ \lfloor{\frac{i}{2}}\rfloor }$.

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

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

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

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

static int lcaPos(int a, int b) {
    if (a == b) return a;
    auto depth = [](int x) -> int {
        
        return 31 - __builtin_clz((unsigned)x);
    };
    int da = depth(a), db = depth(b);
    if (da > db) a >>= (da - db);
    else if (db > da) b >>= (db - da);
    while (a != b) {
        a >>= 1;
        b >>= 1;
    }
    return a;
}

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

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

    int H = 0;
    try {
        H = inf.readInt(3, 18, "h");
    } catch (...) {
        
        query_limit = 0;
        log_metrics();
        quitf(_fail, "Failed to read h from hidden input");
    }

    int n = (1 << H) - 1;
    vector<int> labelAtPos(n + 1, 0);
    vector<int> posOfLabel(n + 1, 0);

    for (int i = 1; i <= n; ++i) {
        int x = 0;
        try {
            x = inf.readInt(1, n, "p[i]");
        } catch (...) {
            query_limit = (long long)n + 420;
            log_metrics();
            quitf(_fail, "Failed to read permutation from hidden input");
        }
        if (posOfLabel[x] != 0) {
            query_limit = (long long)n + 420;
            log_metrics();
            quitf(_fail, "Hidden input permutation has duplicates");
        }
        labelAtPos[i] = x;
        posOfLabel[x] = i;
    }

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

    
    log_metrics();

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

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

        if (cmd == "?") {
            long long u_ll, v_ll, w_ll;
            if (!(cin >> u_ll >> v_ll >> w_ll)) {
                finish(_pe, "Malformed query: expected three integers after '?'");
            }

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

            auto invalid = [&]() -> void {
                cout << "-1\n";
                cout.flush();
                finish(_wa, "Invalid query");
            };

            if (u_ll < 1 || u_ll > n || v_ll < 1 || v_ll > n || w_ll < 1 || w_ll > n) invalid();
            int u = (int)u_ll, v = (int)v_ll, w = (int)w_ll;
            if (u == v || u == w || v == w) invalid();

            int pu = posOfLabel[u];
            int pv = posOfLabel[v];
            int pw = posOfLabel[w];
            if (pu <= 0 || pv <= 0 || pw <= 0) invalid(); 

            int a = lcaPos(pu, pv);
            int b = lcaPos(pu, pw);
            int c = lcaPos(pv, pw);

            int ansPos;
            if (a == b) ansPos = c;
            else if (a == c) ansPos = b;
            else ansPos = a;

            int ansLabel = labelAtPos[ansPos];
            if (ansLabel < 1 || ansLabel > n) {
                finish(_fail, "Internal error: computed answer label out of range");
            }

            cout << ansLabel << "\n";
            cout.flush();
        } else if (cmd == "!") {
            long long r_ll;
            if (!(cin >> r_ll)) {
                finish(_pe, "Malformed answer: expected integer after '!'");
            }
            if (r_ll < 1 || r_ll > n) {
                finish(_wa, "Answer out of range");
            }
            int r = (int)r_ll;
            int correct = labelAtPos[1];
            if (r == correct) {
                finish(_ok, "Correct");
            } else {
                finish(_wa, "Wrong root");
            }
        } else {
            finish(_pe, "Unknown command (expected '?' or '!')");
        }
    }
}


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

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

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

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

struct SplitMix64 {
    uint64_t x;
    explicit SplitMix64(uint64_t seed) : x(seed) {}
    uint64_t nextU64() {
        uint64_t z = (x += 0x9e3779b97f4a7c15ULL);
        z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
        z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
        return z ^ (z >> 31);
    }
};

static int lca_heap(int a, int b) {
    while (a != b) {
        if (a > b) a >>= 1;
        else b >>= 1;
    }
    return a;
}

static int lca_rerooted(int u, int v, int w) {
    int a = lca_heap(u, v);
    int b = lca_heap(u, w);
    int c = lca_heap(v, w);
    if (a == b) return c;
    if (a == c) return b;
    return a;
}

struct JudgeState {
    int H = 0;
    int n = 0;

    bool built = false;
    bool has_given_perm = false;

    vector<int> labelAtPos; 
    vector<int> posOfLabel; 

    void buildInverse() {
        posOfLabel.assign(n + 1, 0);
        for (int pos = 1; pos <= n; ++pos) {
            int lab = labelAtPos[pos];
            if (lab < 1 || lab > n) finish(_fail, "internal: label out of range while building inverse");
            if (posOfLabel[lab] != 0) finish(_fail, "internal: duplicate label while building inverse");
            posOfLabel[lab] = pos;
        }
        for (int lab = 1; lab <= n; ++lab) {
            if (posOfLabel[lab] == 0) finish(_fail, "internal: missing label while building inverse");
        }
        built = true;
    }

    void buildDeterministicPermutation(uint64_t seed) {
        vector<int> a(n);
        iota(a.begin(), a.end(), 1);

        SplitMix64 rng(seed);
        for (int i = n - 1; i > 0; --i) {
            uint64_t r = rng.nextU64();
            int j = (int)(r % (uint64_t)(i + 1));
            swap(a[i], a[j]);
        }

        labelAtPos.assign(n + 1, 0);
        for (int pos = 1; pos <= n; ++pos) labelAtPos[pos] = a[pos - 1];

        if (n >= 2 && labelAtPos[1] == 1) {
            for (int pos = 2; pos <= n; ++pos) {
                if (labelAtPos[pos] != 1) {
                    swap(labelAtPos[1], labelAtPos[pos]);
                    break;
                }
            }
        }
        buildInverse();
    }

    void ensureBuiltDefault() {
        if (built) return;
        
        uint64_t seed = 0xcbf29ce484222325ULL ^ (uint64_t)H * 0x9e3779b97f4a7c15ULL;
        buildDeterministicPermutation(seed);
    }

    void ensureBuiltFromFirstQuery(long long u, long long v, long long w) {
        if (built) return;
        
        uint64_t seed = 0x243f6a8885a308d3ULL;
        seed ^= (uint64_t)H * 0x9e3779b97f4a7c15ULL;
        seed ^= (uint64_t)u * 0xbf58476d1ce4e5b9ULL;
        seed ^= (uint64_t)v * 0x94d049bb133111ebULL;
        seed ^= (uint64_t)w * 0x2545F4914F6CDD1DULL;
        buildDeterministicPermutation(seed);
    }
};

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

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

    JudgeState st;

    st.H = inf.readInt(3, 18, "h");
    st.n = (1 << st.H) - 1;
    query_limit = (long long)st.n + 420;

    
    log_metrics();

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

    
    if (!inf.seekEof()) {
        st.has_given_perm = true;
        st.labelAtPos.assign(st.n + 1, 0);
        for (int pos = 1; pos <= st.n; ++pos) {
            st.labelAtPos[pos] = inf.readInt(1, st.n, ("p[" + to_string(pos) + "]").c_str());
        }
        st.buildInverse();
    }
    
    
    
    if (!st.built) {
        st.ensureBuiltDefault();
        st.has_given_perm = true;
    }

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

    string cmd;
    while (true) {
        if (!(cin >> cmd)) break;

        if (cmd == "?") {
            long long u, v, w;
            if (!(cin >> u >> v >> w)) {
                finish(_pe, "could not read u v w after '?'");
            }
            if (u < 1 || u > st.n || v < 1 || v > st.n || w < 1 || w > st.n) {
                cout << -1 << '\n';
                cout.flush();
                finish(_pe, "query labels out of range");
            }
            if (u == v || u == w || v == w) {
                cout << -1 << '\n';
                cout.flush();
                finish(_pe, "query labels are not distinct");
            }

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

            int pu = st.posOfLabel[(int)u];
            int pv = st.posOfLabel[(int)v];
            int pw = st.posOfLabel[(int)w];

            int ansPos = lca_rerooted(pu, pv, pw);
            int ansLabel = st.labelAtPos[ansPos];

            cout << ansLabel << '\n';
            cout.flush();
        } else if (cmd == "!") {
            long long r;
            if (!(cin >> r)) {
                finish(_pe, "could not read r after '!'");
            }
            if (r < 1 || r > st.n) {
                finish(_pe, "final answer out of range");
            }

            int realRootLabel = st.labelAtPos[1];
            if ((int)r != realRootLabel) {
                finish(_wa, "wrong root");
            } else {
                finish(_ok, "correct");
            }
        } else {
            finish(_pe, "invalid command token (expected '?' or '!')");
        }
    }

    finish(_pe, "contestant terminated without final answer");
}


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

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

static vector<int> makeLabelsShuffled(int n) {
    vector<int> lab(n);
    iota(lab.begin(), lab.end(), 1);
    fisherYatesShuffle(lab);
    return lab;
}

static vector<int> positionsByDepthAlt(int H, int n) {
    vector<int> pos;
    pos.reserve(n);
    for (int d = 0; d < H; ++d) {
        int L = 1 << d;
        int R = min(n, (1 << (d + 1)) - 1);
        if ((d & 1) == 0) {
            for (int i = L; i <= R; ++i) pos.push_back(i);
        } else {
            for (int i = R; i >= L; --i) pos.push_back(i);
        }
    }
    return pos;
}

static void inorderDfs(int v, int n, vector<int>& out) {
    if (v > n) return;
    inorderDfs(v * 2, n, out);
    out.push_back(v);
    inorderDfs(v * 2 + 1, n, out);
}

static vector<int> positionsInorder(int n) {
    vector<int> pos;
    pos.reserve(n);
    inorderDfs(1, n, pos);
    return pos;
}

static long long gcdll(long long a, long long b) {
    while (b) {
        long long t = a % b;
        a = b;
        b = t;
    }
    return a;
}

static void ensureRootNotOne(vector<int>& p, int n) {
    if (n <= 1) return;
    if (p[1] != 1) return;
    int j = rnd.next(2, n);
    for (int it = 0; it < 20 && p[j] == 1; ++it) j = rnd.next(2, n);
    if (p[j] == 1) {
        for (int i = 2; i <= n; ++i) if (p[i] != 1) { j = i; break; }
    }
    swap(p[1], p[j]);
}

static void validatePermutationOrDie(const vector<int>& p, int n) {
    vector<char> used(n + 1, 0);
    for (int i = 1; i <= n; ++i) {
        int x = p[i];
        if (x < 1 || x > n) quitf(_fail, "Permutation value out of range at i=%d: %d", i, x);
        if (used[x]) quitf(_fail, "Duplicate label in permutation: %d", x);
        used[x] = 1;
    }
}

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

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

    int H = opt<int>("h", -1);
    if (H == -1) {
        if (seed == 1) H = 3;
        else if (seed == 2) H = 18;
        else if (seed == 3) H = 18;
        else {
            int roll = rnd.next(0, 99);
            if (roll < 88) H = 18;
            else if (roll < 96) H = 17;
            else H = rnd.next(3, 18);
        }
    }
    if (H < 3 || H > 18) quitf(_fail, "h out of range: %d", H);

    
    
    if (mode != "non" && mode != "adp") quitf(_fail, "Unknown mode: %s", mode.c_str());

    int n = (1 << H) - 1;
    vector<int> p(n + 1, 0);

    if (seed == 1) {
        
        
        if (H != 3) H = 3, n = 7, p.assign(n + 1, 0);
        vector<int> fixed = {0, 4, 7, 2, 6, 1, 5, 3};
        for (int i = 1; i <= n; ++i) p[i] = fixed[i];
    } else if (seed == 2) {
        
        p[1] = n;
        int leafStart = 1 << (H - 1);

        vector<int> pos;
        pos.reserve(n - 1);
        auto addInterleave = [&](int L, int R) {
            while (L <= R) {
                pos.push_back(L);
                if (L == R) break;
                pos.push_back(R);
                ++L; --R;
            }
        };

        addInterleave(leafStart, n);
        addInterleave(2, leafStart - 1);

        if ((int)pos.size() != n - 1) quitf(_fail, "pos size mismatch in seed2: %d vs %d", (int)pos.size(), n - 1);

        int lab = 1;
        for (int idx : pos) p[idx] = lab++;
    } else if (seed == 3) {
        
        for (int i = 1; i <= n; ++i) p[i] = i;
        int leafStart = 1 << (H - 1);
        swap(p[1], p[leafStart]);
    } else {
        int pattern = opt<int>("pattern", -1);
        if (pattern == -1) pattern = rnd.next(0, 5);

        if (pattern == 0) {
            
            vector<int> labels = makeLabelsShuffled(n);
            for (int i = 1; i <= n; ++i) p[i] = labels[i - 1];
        } else if (pattern == 1) {
            
            vector<int> labels = makeLabelsShuffled(n);
            vector<int> pos = positionsByDepthAlt(H, n);
            for (int i = 0; i < n; ++i) p[pos[i]] = labels[i];
        } else if (pattern == 2) {
            
            vector<int> labels = makeLabelsShuffled(n);
            vector<int> pos = positionsInorder(n);
            for (int i = 0; i < n; ++i) p[pos[i]] = labels[i];
        } else if (pattern == 3) {
            
            long long nn = n;
            long long a = rnd.next(1, n - 1);
            long long b = rnd.next(0, n - 1);
            int tries = 0;
            while (gcdll(a, nn) != 1) {
                a = rnd.next(1, n - 1);
                if (++tries > 10000) quitf(_fail, "Could not find coprime a for n=%d", n);
            }
            for (int i = 1; i <= n; ++i) {
                long long x = (a * (long long)(i - 1) + b) % nn;
                p[i] = (int)x + 1;
            }
        } else if (pattern == 4) {
            
            vector<int> depth(n + 1, 0);
            for (int i = 2; i <= n; ++i) depth[i] = depth[i / 2] + 1;

            long long nn = n;
            long long a = rnd.next(1, n - 1);
            long long b = rnd.next(0, n - 1);
            int tries = 0;
            while (gcdll(a, nn) != 1) {
                a = rnd.next(1, n - 1);
                if (++tries > 10000) quitf(_fail, "Could not find coprime a for n=%d", n);
            }

            vector<int> base(n + 1, 0);
            for (int i = 1; i <= n; ++i) {
                long long x = (a * (long long)(i - 1) + b) % nn;
                base[i] = (int)x + 1;
            }

            int k = rnd.next(2, 6);
            vector<pair<int,int>> swaps; 
            swaps.reserve(k);
            int maxInternal = (1 << (H - 1)) - 1; 
            for (int t = 0; t < k; ++t) {
                int x = rnd.next(1, maxInternal);
                int dx = depth[x];
                swaps.push_back({x, dx});
            }

            auto inSubtree = [&](int node, int x) -> bool {
                int j = node;
                while (j > x) j /= 2;
                return j == x;
            };

            for (int i = 1; i <= n; ++i) {
                int pos = i;
                for (auto [x, dx] : swaps) {
                    if (pos != x && pos >= x && inSubtree(pos, x)) {
                        int di = depth[pos];
                        int bit = di - (dx + 1);
                        pos ^= (1 << bit);
                    }
                }
                p[pos] = base[i];
            }
        } else {
            
            vector<int> labels;
            labels.reserve(n);
            int L = 1, R = n;
            while (L <= R) {
                labels.push_back(R--);
                if (L <= R) labels.push_back(L++);
            }
            for (int i = 1; i <= n; ++i) p[i] = labels[i - 1];
        }
    }

    ensureRootNotOne(p, n);
    validatePermutationOrDie(p, n);

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