Problem: cf1617_d2
Difficulty: medium
Categories: greedy, math
Time limit: 3000 ms, memory limit: 256 MB

This is an interactive problem. The only difference between the easy and hard version is the limit on number of questions.

There are $n$ players labelled from $1$ to $n$. It is guaranteed that $n$ is a multiple of $3$.

Among them, there are $k$ impostors and $n-k$ crewmates. The number of impostors, $k$, is not given to you. It is guaranteed that $\frac{n}{3} < k < \frac{2n}{3}$.

In each question, you can choose three distinct integers $a$, $b$, $c$ ($1 \le a, b, c \le n$) and ask: "Among the players labelled $a$, $b$ and $c$, are there more impostors or more crewmates?" You will be given the integer $0$ if there are more impostors than crewmates, and $1$ otherwise.

Find the number of impostors $k$ and the indices of players that are impostors after asking at most $n+6$ questions.

The jury is adaptive, which means the indices of impostors may not be fixed beforehand and can depend on your questions. It is guaranteed that there is at least one set of impostors which fulfills the constraints and the answers to your questions at any time.

Input

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.

The first and only line of each test case contains a single integer $n$ ($6 \le n < 10^4$, $n$ is a multiple of $3$) — the number of players.

It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^4$.

Interaction

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

Then you are allowed to make at most $n+6$ questions in the following way:

"? a b c" ($1 \le a, b, c \le n$, $a$, $b$ and $c$ are pairwise distinct).

After each one, you should read an integer $r$, which is equal to $0$ if there are more impostors than crewmates among players labelled $a$, $b$ and $c$, and equal to $1$ otherwise.

Answer $-1$ instead of $0$ or $1$ means that you 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.

When you have found the indices of all impostors, print a single line "! " (without quotes), followed by the number of impostors $k$, followed by $k$ integers representing the indices of the impostors. Please note that you must print all this information on the same line.

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

After printing the queries and answers do not forget to output end of line and flush the output buffer. Otherwise, you will get the Idleness limit exceeded verdict. To do flush use:

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

Example

Input

```
2
6

0

1

9

1
```

Output

```
? 1 2 3

? 3 4 5

! 3 4 1 2

? 7 1 9

! 4 2 3 6 8
```

Note

Explanation for example interaction (note that this example only exists to demonstrate the interaction procedure and does not provide any hint for the solution):

For the first test case:

Question "? 1 2 3" returns $0$, so there are more impostors than crewmates among players $1$, $2$ and $3$.

Question "? 3 4 5" returns $1$, so there are more crewmates than impostors among players $3$, $4$ and $5$.

Outputting "! 3 4 1 2" means that one has found all the impostors, by some miracle. There are $k = 3$ impostors. The players who are impostors are players $4$, $1$ and $2$.

For the second test case:

Question "? 7 1 9" returns $1$, so there are more crewmates than impostors among players $7$, $1$ and $9$.

Outputting "! 4 2 3 6 8" means that one has found all the impostors, by some miracle. There are $k = 4$ impostors. The players who are impostors are players $2$, $3$, $6$ and $8$.

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

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

    
    int t = inf.readInt();
    
    cout << t << endl;

    for (int i = 0; i < t; i++) {
        
        int n = inf.readInt();
        
        
        
        query_limit += (n + 6);
        log_metrics(); 

        
        vector<int> roles(n + 1);
        vector<int> impostors;
        for (int j = 1; j <= n; j++) {
            roles[j] = inf.readInt();
            if (roles[j] == 0) {
                impostors.push_back(j);
            }
        }
        
        sort(impostors.begin(), impostors.end());

        
        cout << n << endl;

        
        while (true) {
            
            
            if (queries > 250000) {
                finish(_pe, "Hard query limit exceeded (infinite loop?)");
            }

            string token;
            cin >> token;
            if (cin.fail()) {
                finish(_pe, "Unexpected EOF from solution");
            }

            if (token == "!") {
                
                int k_ans;
                if (!(cin >> k_ans)) finish(_pe, "Failed to read k");
                
                vector<int> ans_indices;
                set<int> seen;
                for (int k = 0; k < k_ans; k++) {
                    int idx;
                    if (!(cin >> idx)) finish(_pe, "Failed to read index");
                    if (seen.count(idx)) finish(_wa, "Duplicate index in output");
                    seen.insert(idx);
                    ans_indices.push_back(idx);
                }
                sort(ans_indices.begin(), ans_indices.end());

                
                if ((int)ans_indices.size() != (int)impostors.size()) {
                    finish(_wa, "Incorrect number of impostors");
                }
                if (ans_indices != impostors) {
                    finish(_wa, "Incorrect set of impostors");
                }

                
                break;
            } else {
                
                int a, b, c;
                if (token == "?") {
                    if (!(cin >> a >> b >> c)) finish(_pe, "Failed to read query arguments");
                } else {
                    
                    try {
                        a = stoi(token);
                    } catch (...) {
                        finish(_pe, "Invalid integer token");
                    }
                    if (!(cin >> b >> c)) finish(_pe, "Failed to read b and c");
                }

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

                
                if (a < 1 || a > n || b < 1 || b > n || c < 1 || c > n) {
                    cout << -1 << endl;
                    finish(_wa, format("Indices out of bounds: %d %d %d", a, b, c));
                }
                if (a == b || a == c || b == c) {
                    cout << -1 << endl;
                    finish(_wa, format("Indices must be distinct: %d %d %d", a, b, c));
                }

                
                
                
                
                int s = roles[a] + roles[b] + roles[c];
                cout << (s <= 1 ? 0 : 1) << endl;
            }
        }
    }

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


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

using namespace std;




static long long total_queries = 0;
static long long total_query_limit = 0;
static const long long HARD_CAP = 200000; 






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


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




int n;
vector<int> roles; 


bool isValid(int a, int b, int c) {
    if (a < 1 || a > n) return false;
    if (b < 1 || b > n) return false;
    if (c < 1 || c > n) return false;
    
    if (a == b || a == c || b == c) return false;
    return true;
}

void solve_test_case() {
    
    n = inf.readInt();

    
    
    
    
    vector<int> input_p(n);
    bool is_adaptive_mode = false;
    for (int i = 0; i < n; i++) {
        input_p[i] = inf.readInt();
        if (input_p[i] == -1) is_adaptive_mode = true;
    }

    
    
    
    
    roles.assign(n, 0);
    if (!is_adaptive_mode) {
        roles = input_p;
    } else {
        
        int min_k = n / 3 + 1;
        int max_k = 2 * n / 3 - 1;

        
        int k = rnd.next(min_k, max_k);
        
        for (int i = 0; i < n; i++) {
            if (i < k) roles[i] = 0; 
            else roles[i] = 1;       
        }
        
        shuffle(roles.begin(), roles.end());
    }

    
    
    total_query_limit += (n + 6);

    
    cout << n << endl;

    
    while (true) {
        
        if (total_queries > HARD_CAP) {
            finish(_pe, "Hard query limit exceeded (infinite loop?)");
        }

        string type;
        if (!(cin >> type)) {
            finish(_pe, "Unexpected end of file from solution");
        }

        if (type == "?") {
            int a, b, c;
            if (!(cin >> a >> b >> c)) {
                finish(_pe, "Invalid query format");
            }

            if (!isValid(a, b, c)) {
                
                cout << -1 << endl;
                finish(_wa, format("Invalid query indices: %d %d %d", a, b, c));
            }

            
            total_queries++;

            
            int imp_count = 0;
            if (roles[a-1] == 0) imp_count++;
            if (roles[b-1] == 0) imp_count++;
            if (roles[c-1] == 0) imp_count++;

            
            
            
            
            int ans = (imp_count >= 2) ? 0 : 1;
            cout << ans << endl;

            
            if (total_queries % 500 == 0) log_metrics();

        } else if (type == "!") {
            int k_claimed;
            if (!(cin >> k_claimed)) finish(_pe, "Invalid answer format (reading k)");

            vector<int> claimed_indices;
            claimed_indices.reserve(k_claimed);
            for (int i = 0; i < k_claimed; i++) {
                int idx;
                if (!(cin >> idx)) finish(_pe, "Invalid answer format (reading indices)");
                claimed_indices.push_back(idx);
            }

            
            int actual_k = 0;
            vector<int> actual_indices;
            for (int i = 0; i < n; i++) {
                if (roles[i] == 0) {
                    actual_k++;
                    actual_indices.push_back(i + 1);
                }
            }

            if (k_claimed != actual_k) {
                finish(_wa, format("Wrong number of impostors: expected %d, found %d", actual_k, k_claimed));
            }

            sort(claimed_indices.begin(), claimed_indices.end());
            sort(actual_indices.begin(), actual_indices.end());

            if (claimed_indices != actual_indices) {
                finish(_wa, "Indices of impostors do not match the hidden instance");
            }

            
            return;

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




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

    
    int t = inf.readInt();
    
    
    cout << t << endl;

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

    
    string dummy;
    if (cin >> dummy) {
        finish(_pe, "Extra output after last test case");
    }

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

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

        
        if (seed_val == 1) {
            n = 6; 
        } else if (seed_val == 2) {
            n = 9999; 
        } else if (seed_val == 3) {
            n = 12; 
        } else {
            
            
            n = 3 * rnd.next(2, 3333);
        }
    }

    
    
    if (n < 6) n = 6;
    if (n % 3 != 0) n -= (n % 3);

    
    cout << 1 << "\n";
    
    
    cout << n << "\n";

    if (mode == "adp") {
        
        
        
        for (int i = 0; i < n; i++) {
            cout << -1 << (i == n - 1 ? "" : " ");
        }
        cout << "\n";
    } else {
        
        
        int min_k = n / 3 + 1;
        int max_k = 2 * n / 3 - 1;
        
        int k;
        
        int type = rnd.next(1, 10);
        if (type == 1) k = min_k;
        else if (type == 2) k = max_k;
        else k = rnd.next(min_k, max_k);
        
        
        vector<int> p(n);
        for (int i = 0; i < n; i++) {
            if (i < k) p[i] = 0; 
            else p[i] = 1;       
        }
        
        
        shuffle(p.begin(), p.end());
        
        
        for (int i = 0; i < n; i++) {
            cout << p[i] << (i == n - 1 ? "" : " ");
        }
        cout << "\n";
    }

    return 0;
}