Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef pair<int, int> ii;
- typedef long long ll;
- #define sz(v) ((int)((v).size()))
- #define all(v) (v).begin(),(v).end()
- int solve(const int n, const function<int(int,int)>& ask) {
- int highestBit = 0;
- for (int i = 0; i <= 30; i++) {
- if (n & (1 << i)) {
- highestBit = i;
- }
- }
- vector<int> indices;
- for (int i = 1; i <= n; i++) {
- indices.push_back(i);
- }
- vector<int> values;
- for (int i = 0; i <= n; i++) {
- values.push_back(i);
- }
- for (int bit = 0; bit <= highestBit; bit++) {
- if (sz(values) == 1) break;
- vector<vector<int>> expected(2);
- for (int x : values) {
- expected[(x >> bit) & 1].push_back(x);
- }
- vector<vector<int>> have(2);
- for (int i : indices) {
- int val = ask(i, bit);
- have[val].push_back(i);
- }
- assert(
- (sz(have[0]) == sz(expected[0])) ^
- (sz(have[1]) == sz(expected[1]))
- );
- if (sz(have[0]) == sz(expected[0])) {
- values = expected[1];
- indices = have[1];
- } else {
- values = expected[0];
- indices = have[0];
- }
- //cerr << "indices: "; for (int x : indices) cerr << x << " "; cerr << endl;
- //cerr << "values: "; for (int x : values) cerr << x << " "; cerr << endl;
- assert(sz(indices) + 1 == sz(values));
- }
- assert(sz(indices) == 0);
- assert(sz(values) == 1);
- return values[0];
- }
- void stress() {
- ofstream log("log.txt");
- const int MAX_N = 1000;
- vector<int> a;
- for (int n = 1; n <= MAX_N; n++) {
- a.resize(n);
- for (int missing = 0; missing <= n; missing++) {
- int now = 0;
- for (int i = 0; i < n; i++) {
- if (now == missing) now++;
- a[i] = now++;
- }
- int questions = 0;
- function<int(int,int)> askEmulator = [&](const int index, const int bit) {
- assert(1 <= index && index <= n);
- questions++;
- int val = (a[index - 1] >> bit) & 1;
- //log << " asking index = " << index << ", bit = " << bit << " -> val = " << val << endl;
- return val;
- };
- log << "===================" << endl;
- log << "n = " << n << ", missing = " << missing << endl;
- //log << "arr = "; for (int x : a) log << x << " "; log << endl;
- log.flush();
- const int res = solve(n, askEmulator);
- log << "res = " << res << ", questions = " << questions << endl;
- if (res != missing) {
- cerr << "ERROR: n = " << n << ", missing = " << missing << ", res = " << res << endl;
- throw;
- }
- }
- if (n % (MAX_N / 100) == 0) {
- cerr << "n = " << n << " is OK" << endl;
- }
- }
- cerr << "Stress completed" << endl;
- }
- int main() {
- //ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
- //cout.setf(ios::fixed); cout.precision(15);
- //stress(); return 0;
- int n;
- cin >> n;
- function<int(int,int)> askIO = [](const int index, const int bit) {
- cout << "? " << index << ' ' << bit << endl;
- int val;
- cin >> val;
- return val;
- };
- int res = solve(n, askIO);
- cout << "! " << res << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment