Problem: cf772_e
Difficulty: hard
Categories: graph, search
Time limit: 2000 ms, memory limit: 256 MB

E. Verifying Kingdom

This is an interactive problem.

The judge has a hidden rooted full binary tree with *n* leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2*n* - 1 nodes in the tree. The leaves of the judge's tree has labels from 1 to *n*. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.

A question consists of printing the label of three distinct leaves *a*1, *a*2, *a*3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let *LCA*(*a*, *b*) denote the node with maximum depth that is a common ancestor of the nodes *a* and *b*.

Consider *X* = *LCA*(*a*1, *a*2), *Y* = *LCA*(*a*2, *a*3), *Z* = *LCA*(*a*3, *a*1). The judge will tell you which one of *X*, *Y*, *Z* has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties.

More specifically, if *X* (or *Y*, *Z* respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively).

You may only ask at most 10·*n* questions.

Input

The first line of input will contain a single integer *n* (3 ≤ *n* ≤ 1 000) — the number of leaves in the tree.

Output

To print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2*n* - 1 integers. The *i*-th integer should be the parent of the *i*-th node, or -1, if it is the root.

Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to *n*. Here, isomorphic means that there exists a permutation π such that node *i* is the parent of node *j* in the judge tree if and only node π(*i*) is the parent of node π(*j*) in your tree.

Interaction

To ask a question, print out three distinct integers *a*1, *a*2, *a*3. These integers should be between 1 and *n*, inclusive.

The judge will respond with a single character, either "X", "Y", "Z".

If the string is "X" (or "Y", "Z" respectively), that means the pair (*a*1, *a*2) (or (*a*2, *a*3), (*a*3, *a*1) respectively) has the deepest *LCA* among the three pairs.

You may only ask a question at most 10·*n* times, otherwise, you will get Wrong Answer.

When you are ready to answer, print out a single integer "-1" on its own line. The next line should contain 2*n* - 1 integers. The *i*-th integer should be the parent of the *i*-th node, or -1, if it is the root. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.

You will get Wrong Answer verdict if

* Your question or answers are not in the format described in this statement.
* You ask strictly more than 10·*n* questions.
* Your question contains duplicate indices.
* Your final answer is not isomorphic to the judge tree.

You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).

To flush you can use (just after printing an integer and end-of-line):

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

If at any moment your program reads -1 as an answer, it should immediately exit normally (for example, by calling exit(0)). You will get Wrong Answer in this case, it means that you made more queries than allowed, or made an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.

Example

Input

```
5  
X  
Z  
Y  
Y  
X
```

Output

```
1 4 2  
1 2 4  
2 4 1  
2 3 5  
2 4 3  
-1  
-1 1 1 2 2 3 3 6 6
```

Note

For the first sample, the judge has the hidden tree:

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

Here is a more readable format of the interaction:

![](https://espresso.codeforces.com/1cfb86747dfd0278bc848ef24aa3a158e4ce0220.png) The last line can also be 8 6 9 8 9 7 -1 6 7.

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




static int n;
static vector<int> judge_parent;      
static vector<vector<int>> judge_adj; 
static vector<int> judge_depth;       
static int judge_root = -1;

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




void build_judge() {
    judge_adj.assign(2 * n, vector<int>());
    judge_depth.assign(2 * n, 0);
    
    for (int i = 1; i < 2 * n; i++) {
        int p = judge_parent[i];
        if (p == -1) {
            judge_root = i;
        } else {
            
            if (p < 1 || p >= 2 * n) {
                
                quitf(_fail, "Judge tree parent out of range");
            }
            judge_adj[p].push_back(i);
        }
    }
    
    if (judge_root == -1) {
        quitf(_fail, "No root found in judge tree");
    }

    
    vector<int> q;
    q.push_back(judge_root);
    judge_depth[judge_root] = 0;
    
    int head = 0;
    while(head < (int)q.size()) {
        int u = q[head++];
        for(int v : judge_adj[u]) {
            judge_depth[v] = judge_depth[u] + 1;
            q.push_back(v);
        }
    }
}

int get_lca(int u, int v) {
    int du = judge_depth[u];
    int dv = judge_depth[v];
    
    while (du > dv) {
        u = judge_parent[u];
        du--;
    }
    while (dv > du) {
        v = judge_parent[v];
        dv--;
    }
    while (u != v) {
        u = judge_parent[u];
        v = judge_parent[v];
    }
    return u;
}





string get_canonical(int u, const vector<vector<int>>& adj) {
    if (adj[u].empty()) return "1";
    
    vector<string> subs;
    for (int v : adj[u]) {
        subs.push_back(get_canonical(v, adj));
    }
    sort(subs.begin(), subs.end());
    
    string res = "0";
    for (const auto& s : subs) res += s;
    return res;
}




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

    
    n = inf.readInt();
    query_limit = 10LL * n;
    
    judge_parent.assign(2 * n, 0);
    for (int i = 1; i < 2 * n; i++) {
        judge_parent[i] = inf.readInt();
    }
    
    build_judge();

    
    cout << n << endl;

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

        
        if (token == "!") {
            continue; 
        }
        
        if (token == "-1") {
            
            break;
        }

        int a1, a2, a3;

        
        if (token == "?") {
            if (!(cin >> a1 >> a2 >> a3)) {
                finish(_wa, "Incomplete query format");
            }
        } else {
            
            try {
                a1 = stoi(token);
            } catch (...) {
                finish(_wa, "Invalid token in query");
            }
            if (a1 == -1) break; 
            
            if (!(cin >> a2 >> a3)) {
                finish(_wa, "Incomplete query format");
            }
        }

        queries++;
        if (queries % 10 == 0) log_metrics(); 
        
        
        if (queries > query_limit + 100) {
             finish(_wa, "Query limit exceeded significantly");
        }

        
        if (a1 < 1 || a1 > n || a2 < 1 || a2 > n || a3 < 1 || a3 > n) {
            finish(_wa, "Query indices must be leaves 1..n");
        }
        if (a1 == a2 || a1 == a3 || a2 == a3) {
            finish(_wa, "Query indices must be distinct");
        }

        
        int X = get_lca(a1, a2);
        int Y = get_lca(a2, a3);
        int Z = get_lca(a3, a1);

        int dX = judge_depth[X];
        int dY = judge_depth[Y];
        int dZ = judge_depth[Z];

        if (dX >= dY && dX >= dZ) cout << "X" << endl;
        else if (dY >= dX && dY >= dZ) cout << "Y" << endl;
        else cout << "Z" << endl;
    }

    
    
    vector<int> user_p(2 * n);
    for (int i = 1; i < 2 * n; i++) {
        if (!(cin >> user_p[i])) {
            finish(_wa, "Incomplete answer (expected 2n-1 integers)");
        }
    }

    
    vector<vector<int>> user_adj(2 * n);
    int user_root = -1;
    int root_count = 0;

    for (int i = 1; i < 2 * n; i++) {
        int p = user_p[i];
        if (p == -1) {
            user_root = i;
            root_count++;
        } else {
            if (p < 1 || p >= 2 * n) finish(_wa, "Parent index out of range");
            if (p == i) finish(_wa, "Self loop in tree");
            user_adj[p].push_back(i);
        }
    }

    if (root_count != 1) finish(_wa, "Tree must have exactly one root");
    if (user_root == -1) finish(_wa, "No root found");

    
    int seen = 0;
    vector<bool> vis(2 * n, false);
    vector<int> q;
    q.push_back(user_root);
    vis[user_root] = true;
    seen++;

    int head = 0;
    while(head < (int)q.size()){
        int u = q[head++];
        for(int v : user_adj[u]){
            if(vis[v]) finish(_wa, "Cycle detected"); 
            vis[v] = true;
            seen++;
            q.push_back(v);
        }
    }

    if (seen != 2 * n - 1) finish(_wa, "Graph is not connected or contains cycles");

    
    int leaves = 0;
    for (int i = 1; i < 2 * n; i++) {
        int deg = user_adj[i].size();
        if (deg == 0) leaves++;
        else if (deg != 2) finish(_wa, "Not a full binary tree (node degree is not 0 or 2)");
    }

    if (leaves != n) finish(_wa, "Wrong number of leaves in reconstructed tree");
    
    
    if (queries > query_limit) {
        finish(_wa, "Query limit exceeded");
    }

    
    
    string code_judge = get_canonical(judge_root, judge_adj);
    string code_user = get_canonical(user_root, user_adj);

    if (code_judge == code_user) {
        finish(_ok, "Correct");
    } else {
        finish(_wa, "Tree is not isomorphic to the hidden tree");
    }

    return 0;
}


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() {
    if (query_limit == 0) return; 
    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 n;
vector<vector<int>> hidden_adj;
vector<int> hidden_parent;
vector<int> hidden_depth;
int hidden_root = -1;




void build_hidden_tree_from_parents(int N, const vector<int>& p) {
    n = N;
    int nodes = 2 * n - 1;
    hidden_adj.assign(nodes + 1, vector<int>());
    hidden_parent = p; 
    hidden_depth.assign(nodes + 1, 0);
    
    hidden_root = -1;
    for (int i = 1; i <= nodes; i++) {
        if (p[i] == -1) {
            hidden_root = i;
        } else {
            hidden_adj[p[i]].push_back(i);
        }
    }
    
    
    function<void(int, int)> dfs = [&](int u, int d) {
        hidden_depth[u] = d;
        for (int v : hidden_adj[u]) dfs(v, d + 1);
    };
    if (hidden_root != -1) dfs(hidden_root, 0);
}


void generate_hidden_tree(int N) {
    n = N;
    
    
    
    
    struct Info { int id; int h; };
    vector<Info> roots;
    for(int i = 1; i <= n; ++i) roots.push_back({i, 0});
    
    
    shuffle(roots.begin(), roots.end());
    
    int next_id = n + 1;
    vector<int> p(2 * n, 0);
    
    
    for (int i = 0; i < n - 1; i++) {
        
        int idx1 = rnd.next(0, (int)roots.size() - 1);
        int idx2 = rnd.next(0, (int)roots.size() - 1);
        while(idx1 == idx2) idx2 = rnd.next(0, (int)roots.size() - 1);
        
        
        if (idx1 > idx2) swap(idx1, idx2);
        
        Info r1 = roots[idx1];
        Info r2 = roots[idx2];
        
        roots.erase(roots.begin() + idx2);
        roots.erase(roots.begin() + idx1);
        
        p[r1.id] = next_id;
        p[r2.id] = next_id;
        
        roots.push_back({next_id, max(r1.h, r2.h) + 1});
        next_id++;
    }
    p[2 * n - 1] = -1; 
    
    build_hidden_tree_from_parents(n, p);
}

int get_lca_depth(int u, int v) {
    if (u == v) return hidden_depth[u];
    
    if (hidden_depth[u] < hidden_depth[v]) swap(u, v);
    while (hidden_depth[u] > hidden_depth[v]) {
        u = hidden_parent[u];
    }
    
    while (u != v) {
        u = hidden_parent[u];
        v = hidden_parent[v];
    }
    return hidden_depth[u];
}




map<pair<int,int>, int> canon_map;

int get_canon_id(pair<int,int> p) {
    if (canon_map.find(p) == canon_map.end()) {
        canon_map[p] = (int)canon_map.size();
    }
    return canon_map[p];
}



int get_tree_hash(int u, const vector<vector<int>>& adj) {
    if (adj[u].empty()) return 0; 
    
    vector<int> children_hashes;
    for (int v : adj[u]) {
        children_hashes.push_back(get_tree_hash(v, adj));
    }
    sort(children_hashes.begin(), children_hashes.end());
    
    
    if (children_hashes.size() != 2) return -1; 
    
    return get_canon_id({children_hashes[0], children_hashes[1]});
}



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

    
    n = inf.readInt();
    
    
    
    if (inf.seekEof()) {
        generate_hidden_tree(n);
    } else {
        vector<int> p(2 * n);
        for (int i = 1; i < 2 * n; i++) {
            p[i] = inf.readInt();
        }
        build_hidden_tree_from_parents(n, p);
    }
    
    query_limit = 10LL * n;
    
    
    cout << n << endl;
    
    
    long long hard_cap = max(200000LL, 10 * query_limit);
    
    while (true) {
        string token;
        if (!(cin >> token)) {
            finish(_wa, "Unexpected end of input (expected query or -1)");
        }
        
        if (token == "-1") {
            break; 
        }
        
        
        int a1, a2, a3;
        try {
            a1 = stoi(token);
        } catch (...) {
            finish(_wa, "Invalid query format (expected integer)");
        }
        
        if (!(cin >> a2 >> a3)) {
            finish(_wa, "Unexpected end of input reading query arguments");
        }
        
        queries++;
        if (queries > hard_cap) {
            finish(_pe, "Hard query limit exceeded");
        }
        
        
        if (a1 < 1 || a1 > n || a2 < 1 || a2 > n || a3 < 1 || a3 > n) {
            finish(_wa, "Query index out of range [1, n]");
        }
        if (a1 == a2 || a1 == a3 || a2 == a3) {
            finish(_wa, "Query indices must be distinct");
        }
        
        
        int dX = get_lca_depth(a1, a2);
        int dY = get_lca_depth(a2, a3);
        int dZ = get_lca_depth(a1, a3);
        
        char ans;
        
        
        
        
        
        
        
        
        
        if (dX >= dY && dX >= dZ) ans = 'X';
        else if (dY >= dX && dY >= dZ) ans = 'Y';
        else ans = 'Z';
        
        cout << ans << endl;
        
        
        if (queries % 100 == 0) log_metrics();
    }
    
    
    
    vector<int> user_p(2 * n);
    for (int i = 1; i < 2 * n; i++) {
        if (!(cin >> user_p[i])) {
            finish(_wa, "Failed to read final answer parent array");
        }
    }
    
    
    int user_nodes = 2 * n - 1;
    vector<vector<int>> user_adj(user_nodes + 1);
    int user_root = -1;
    vector<int> user_degree(user_nodes + 1, 0);
    
    for (int i = 1; i <= user_nodes; i++) {
        int p = user_p[i];
        if (p == -1) {
            if (user_root != -1) finish(_wa, "Output contains multiple roots");
            user_root = i;
        } else {
            if (p < 1 || p > user_nodes) finish(_wa, "Parent index out of range in final answer");
            user_adj[p].push_back(i); 
            user_degree[p]++;
        }
    }
    
    if (user_root == -1) finish(_wa, "Output tree has no root");
    
    
    
    
    int edges = 0;
    for (int i = 1; i <= user_nodes; i++) {
        if (user_degree[i] != 0 && user_degree[i] != 2) {
            finish(_wa, "Output is not a full binary tree (nodes must have 0 or 2 children)");
        }
        if (user_degree[i] > 0) edges += user_degree[i];
    }
    
    
    vector<int> q;
    vector<bool> visited(user_nodes + 1, false);
    q.push_back(user_root);
    visited[user_root] = true;
    size_t head = 0;
    while(head < q.size()){
        int u = q[head++];
        for(int v : user_adj[u]){
            if(visited[v]) finish(_wa, "Output tree contains a cycle");
            visited[v] = true;
            q.push_back(v);
        }
    }
    
    if (q.size() != user_nodes) finish(_wa, "Output tree is disconnected or not a single component");

    
    
    canon_map.clear();
    
    
    int h1 = get_tree_hash(hidden_root, hidden_adj);
    int h2 = get_tree_hash(user_root, user_adj);
    
    if (h1 == -1) finish(_wa, "Internal Error: Hidden tree invalid"); 
    if (h2 == -1) finish(_wa, "Output tree structure mismatch (hash failed)"); 
    
    if (h1 == h2) {
        finish(_ok, "Correct (Isomorphic)");
    } else {
        finish(_wa, "Output tree is not isomorphic to the hidden tree");
    }

    return 0;
}


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

using namespace std;

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

    
    
    string mode = opt<string>("mode", "non");
    int n_opt = opt<int>("n", 0);
    
    
    int seed = atoi(argv[1]);

    int n;
    string type;

    
    if (n_opt > 0) {
        n = n_opt;
        type = "random";
    } else {
        if (seed == 1) {
            n = 3;
            type = "random";
        } else if (seed == 2) {
            n = 1000;
            type = "caterpillar";
        } else if (seed == 3) {
            n = 1000;
            type = "balanced";
        } else {
            
            n = rnd.next(500, 1000);
            int t = rnd.next(0, 2);
            if (t == 0) type = "random";
            else if (t == 1) type = "caterpillar";
            else type = "balanced";
        }
    }

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

    
    
    
    

    struct NodeInfo {
        int id;
        int height;
    };
    
    vector<NodeInfo> roots;
    for (int i = 1; i <= n; i++) {
        roots.push_back({i, 0});
    }

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

    vector<int> p(2 * n); 
    int next_internal = n + 1;

    
    for (int step = 0; step < n - 1; step++) {
        int i1 = -1, i2 = -1;
        
        if (type == "random") {
            
            i1 = rnd.next(0, (int)roots.size() - 1);
            i2 = rnd.next(0, (int)roots.size() - 1);
            while (i1 == i2) {
                i2 = rnd.next(0, (int)roots.size() - 1);
            }
        } else if (type == "caterpillar") {
            
            vector<int> leaf_indices;
            for(int i=0; i<(int)roots.size(); ++i) {
                if(roots[i].height == 0) leaf_indices.push_back(i);
            }
            
            
            if (!leaf_indices.empty()) {
                i1 = leaf_indices[rnd.next(0, (int)leaf_indices.size() - 1)];
            } else {
                i1 = rnd.next(0, (int)roots.size() - 1);
            }

            
            int max_h = -1;
            int bi = -1;
            for(int i=0; i<(int)roots.size(); ++i) {
                if (i == i1) continue;
                if (roots[i].height > max_h) {
                    max_h = roots[i].height;
                    bi = i;
                }
            }
            
            if (bi == -1) {
                bi = rnd.next(0, (int)roots.size() - 1);
                while (bi == i1) bi = rnd.next(0, (int)roots.size() - 1);
            }
            i2 = bi;

        } else { 
            
            i1 = 0;
            for(int i=1; i<(int)roots.size(); ++i) {
                if (roots[i].height < roots[i1].height) i1 = i;
            }
            
            i2 = -1;
            for(int i=0; i<(int)roots.size(); ++i) {
                if (i == i1) continue;
                if (i2 == -1 || roots[i].height < roots[i2].height) i2 = i;
            }
        }

        
        if (i1 > i2) swap(i1, i2);

        int id1 = roots[i1].id;
        int id2 = roots[i2].id;
        int h = max(roots[i1].height, roots[i2].height) + 1;

        
        roots.erase(roots.begin() + i2);
        roots.erase(roots.begin() + i1);

        
        p[id1] = next_internal;
        p[id2] = next_internal;
        
        
        roots.push_back({next_internal, h});

        next_internal++;
    }

    
    p[2 * n - 1] = -1;

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

    return 0;
}