Problem: cf1970_d3
Difficulty: hard
Categories: data structures, math
Time limit: 10000 ms, memory limit: 256 MB

The only difference between the versions of this problem is the maximum value of $n$.

Professor Vector is preparing to teach her Arithmancy class. She needs to prepare $n$ distinct magic words for the class. Each magic word is a string consisting of characters X and O. A spell is a string created by concatenating two magic words together. The power of a spell is equal to the number of its different non-empty substrings. For example, the power of the spell XOXO is equal to 7, because it has 7 different substrings: X, O, XO, OX, XOX, OXO and XOXO.

Each student will create their own spell by concatenating two magic words. Since the students are not very good at magic yet, they will choose each of the two words independently and uniformly at random from the $n$ words provided by Professor Vector. It is therefore also possible that the two words a student chooses are the same. Each student will then compute the power of their spell, and tell it to Professor Vector. In order to check their work, and of course to impress the students, Professor Vector needs to find out which two magic words and in which order were concatenated by each student.

Your program needs to perform the role of Professor Vector: first, create $n$ distinct magic words, and then handle multiple requests where it is given the spell power and needs to determine the indices of the two magic words, in the correct order, that were used to create the corresponding spell.

Interaction

This is an interactive problem.

First, your program should read a single integer $n$ ($1 \le n \le 1000$), the number of magic words to prepare. Then, it should print $n$ magic words it has created, one per line. The magic words must be distinct, each magic word must have at least 1 and at most $30\cdot n$ characters, and each character must be either X or O. We will denote the $i$-th magic word you printed as $w_i$ ($1 \le i \le n$).

Then, your program should read a single integer $q$ ($1 \le q \le 1000$), the number of students in the class. Then, it should repeat the following process $q$ times, one per student.

For the $j$-th student, it should first read a single integer $p_j$, the power of their spell. It is guaranteed that this number is computed by choosing two indices $u_j$ and $v_j$ independently and uniformly at random between 1 and $n$ inclusive, concatenating $w_{u_j}$ and $w_{v_j}$, and finding the number of different non-empty substrings of the resulting string. Then, your program must print the numbers $u_j$ and $v_j$, in this order ($1 \le u_j, v_j \le n$).

Note that it is not enough to find any two magic words that concatenate into a spell with the given power. You must find the exact words used by the student in the exact order.

Remember to flush the output stream after printing all magic words and after printing $u_j$ and $v_j$ for each student.

Example

Input

```
2

2
15

11
```

Output

```
XOXO
X

1 1

2 1
```

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;



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


struct SuffixAutomaton {
    struct State {
        int len, link;
        int next[2]; 
    };

    vector<State> st;
    int sz;
    int last;

    void init() {
        st.clear();
        
        
        
        st.reserve(150000);
        reset();
    }

    void reset() {
        
        st.clear();
        
        st.push_back({0, -1, {-1, -1}});
        sz = 1;
        last = 0;
    }

    void extend(char c) {
        int cur = sz++;
        st.emplace_back();
        
        st[cur].len = st[last].len + 1;
        st[cur].next[0] = st[cur].next[1] = -1;
        st[cur].link = -1;

        int p = last;
        int code = (c == 'X' ? 1 : 0);
        
        while (p != -1 && st[p].next[code] == -1) {
            st[p].next[code] = cur;
            p = st[p].link;
        }
        if (p == -1) {
            st[cur].link = 0;
        } else {
            int q = st[p].next[code];
            if (st[p].len + 1 == st[q].len) {
                st[cur].link = q;
            } else {
                int clone = sz++;
                st.emplace_back();
                st[clone].len = st[p].len + 1;
                st[clone].next[0] = st[q].next[0];
                st[clone].next[1] = st[q].next[1];
                st[clone].link = st[q].link;
                
                while (p != -1 && st[p].next[code] == q) {
                    st[p].next[code] = clone;
                    p = st[p].link;
                }
                st[q].link = st[cur].link = clone;
            }
        }
        last = cur;
    }

    long long count_distinct() {
        long long ans = 0;
        
        for (int i = 1; i < sz; i++) {
            ans += (long long)(st[i].len - st[st[i].link].len);
        }
        return ans;
    }
};

SuffixAutomaton sa;

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

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

    
    int n_in = inf.readInt(1, 1000, "n");
    int n = min(n_in, 30);  
    int q_val = inf.readInt(1, 1000, "q");
    
    
    
    query_limit = q_val;
    log_metrics(); 

    
    cout << n << endl;

    
    vector<string> w(n + 1);
    set<string> seen;
    
    for (int i = 1; i <= n; ++i) {
        if (!(cin >> w[i])) {
            finish(_pe, "Solution terminated before providing all magic words");
        }
        
        long long max_len = 30LL * n;
        if (w[i].length() < 1) { 
            finish(_wa, format("Magic word %d is empty", i));
        }
        if (w[i].length() > max_len) {
            finish(_wa, format("Magic word %d too long: %d > %d", i, (int)w[i].length(), (int)max_len));
        }
        for (char c : w[i]) {
            if (c != 'X' && c != 'O') {
                finish(_wa, format("Magic word %d contains invalid char '%c'", i, c));
            }
        }
        if (seen.count(w[i])) {
            finish(_wa, format("Magic word %d is not distinct", i));
        }
        seen.insert(w[i]);
    }

    
    cout << q_val << endl;

    
    sa.init();

    
    for (int k = 0; k < q_val; ++k) {
        
        int u_in = inf.readInt(1, n_in, "u");
        int v_in = inf.readInt(1, n_in, "v");
        int u = (u_in - 1) % n + 1;
        int v = (v_in - 1) % n + 1;

        
        string spell = w[u] + w[v];
        
        
        sa.reset();
        for (char c : spell) {
            sa.extend(c);
        }
        long long power = sa.count_distinct();

        
        cout << power << endl;

        
        
        string token;
        if (!(cin >> token)) {
            finish(_pe, "Solution terminated early (expected u)");
        }
        
        int u_ans, v_ans;
        
        
        if (token == "!" || token == "?") {
            if (!(cin >> token)) finish(_pe, "Solution terminated early after prefix");
        }
        
        
        try {
            size_t idx;
            u_ans = stoi(token, &idx);
            if (idx != token.size()) finish(_wa, "Invalid integer format for u: " + token);
        } catch (...) {
            finish(_wa, "Invalid integer format for u: " + token);
        }

        
        if (!(cin >> token)) {
             finish(_pe, "Solution terminated early (expected v)");
        }
        try {
            size_t idx;
            v_ans = stoi(token, &idx);
             if (idx != token.size()) finish(_wa, "Invalid integer format for v: " + token);
        } catch (...) {
            finish(_wa, "Invalid integer format for v: " + token);
        }

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

        
        if (u_ans != u || v_ans != v) {
            finish(_wa, format("Wrong answer on query %d. Expected %d %d, got %d %d", k+1, u, v, u_ans, v_ans));
        }
    }

    finish(_ok, format("Passed %d queries", q_val));
    return 0;
}


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

using namespace std;


static int queries_count = 0;
static int query_limit_val = 0;



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


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


struct SAM {
    static const int MAXLEN = 60005; 
    int len[MAXLEN * 2];
    int link[MAXLEN * 2];
    int next_state[MAXLEN * 2][2]; 
    int sz, last;

    void init() {
        len[0] = 0;
        link[0] = -1;
        next_state[0][0] = next_state[0][1] = -1;
        sz = 1;
        last = 0;
    }

    void extend(char c) {
        int val = (c == 'X' ? 1 : 0);
        int cur = sz++;
        len[cur] = len[last] + 1;
        next_state[cur][0] = next_state[cur][1] = -1;
        int p = last;
        while (p != -1 && next_state[p][val] == -1) {
            next_state[p][val] = cur;
            p = link[p];
        }
        if (p == -1) {
            link[cur] = 0;
        } else {
            int q = next_state[p][val];
            if (len[p] + 1 == len[q]) {
                link[cur] = q;
            } else {
                int clone = sz++;
                len[clone] = len[p] + 1;
                next_state[clone][0] = next_state[q][0];
                next_state[clone][1] = next_state[q][1];
                link[clone] = link[q];
                while (p != -1 && next_state[p][val] == q) {
                    next_state[p][val] = clone;
                    p = link[p];
                }
                link[q] = link[cur] = clone;
            }
        }
        last = cur;
    }

    long long count_distinct() {
        long long ans = 0;
        for (int i = 1; i < sz; i++) {
            ans += (long long)(len[i] - len[link[i]]);
        }
        return ans;
    }
} sam;

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

    
    int n_in = inf.readInt(1, 1000, "n");
    int n = min(n_in, 30);  

    
    
    cout << n << endl;

    
    vector<string> w(n);
    vector<string*> ptrs(n);
    for (int i = 0; i < n; i++) {
        
        if (!(cin >> w[i])) {
            finish(_pe, "Unexpected EOF reading magic words");
        }
        
        
        if (w[i].length() < 1 || w[i].length() > 30ULL * n) {
            finish(_pe, format("Word %d length %d is out of bounds [1, %d]", i + 1, (int)w[i].length(), 30 * n));
        }

        
        for (char c : w[i]) {
            if (c != 'X' && c != 'O') {
                finish(_pe, "Magic words must only contain 'X' and 'O'");
            }
        }
        ptrs[i] = &w[i];
    }

    
    
    sort(ptrs.begin(), ptrs.end(), [](string* a, string* b) {
        return *a < *b;
    });
    for (int i = 0; i < n - 1; i++) {
        if (*ptrs[i] == *ptrs[i + 1]) {
            finish(_pe, "Magic words must be distinct");
        }
    }

    
    int q = inf.readInt(1, 1000, "q");
    query_limit_val = q;
    log_metrics(); 

    
    
    vector<pair<int, int>> predefined;
    inf.skipBlanks();
    while (!inf.eof()) {
        int u = inf.readInt(1, n_in, "u");
        int v = inf.readInt(1, n_in, "v");
        predefined.push_back({u, v});
        inf.skipBlanks();
    }

    
    cout << q << endl;

    
    
    
    rnd.setSeed(n * 239017LL + q * 1023LL + 12345LL);

    
    for (int j = 0; j < q; j++) {
        int u_in, v_in;
        if (j < (int)predefined.size()) {
            u_in = predefined[j].first;
            v_in = predefined[j].second;
        } else {
            
            u_in = rnd.next(1, n);
            v_in = rnd.next(1, n);
        }

        int u = (u_in - 1) % n + 1;
        int v = (v_in - 1) % n + 1;

        
        string s = w[u - 1] + w[v - 1];
        sam.init();
        for (char c : s) sam.extend(c);
        long long power = sam.count_distinct();

        
        cout << power << endl;

        
        int user_u, user_v;
        if (!(cin >> user_u >> user_v)) {
            finish(_pe, "Unexpected EOF reading answer");
        }

        queries_count++;
        
        if (queries_count % 50 == 0) log_metrics();

        
        
        if (user_u != u || user_v != v) {
            finish(_wa, format("Wrong answer on query %d. Expected: %d %d, Found: %d %d", j + 1, u, v, user_u, user_v));
        }
    }

    finish(_ok, "Correct");
    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_in = opt<int>("n", -1);
    int q_in = opt<int>("q", -1);

    
    
    const int N_MAX = 30;

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

    int n, q;

    
    if (n_in != -1) {
        n = max(1, min(n_in, N_MAX));
    } else {
        
        if (seed_val == 1) n = 1;                   
        else if (seed_val == 2) n = N_MAX;          
        else if (seed_val == 3) n = N_MAX;
        else if (seed_val == 4) n = N_MAX;
        else {
            
            
            if (rnd.next(100) < 80)
                n = rnd.wnext(1, N_MAX, 20);
            else
                n = rnd.next(1, N_MAX);
        }
    }

    
    if (q_in != -1) {
        q = max(1, q_in);
    } else {
        if (seed_val == 1) q = 1;
        else if (seed_val == 2) q = 1000;           
        else {
            
            q = rnd.next(1, 1000);
        }
    }

    
    cout << n << endl;
    cout << q << endl;

    
    
    if (mode == "non") {
        for (int i = 0; i < q; ++i) {
            int u = rnd.next(1, n);
            int v = rnd.next(1, n);
            cout << u << " " << v << "\n";
        }
    }
    
    
    
    return 0;
}