We'd like to thank you all for participating in the contest, and hope you enjoyed it. Hope to see you again soon!
Author: C0de_Beast
Tutorial
We have to convert an hidden number $$$x$$$ into a given number $$$k$$$ with in $$$31$$$ queries, where $$$x$$$ and $$$k$$$ both lies in range $$$[1,10^9]$$$, which can be represented in $$$30$$$ bits.
Our last move will obviously be to convert the hidden number to $$$k$$$, thus we will have to figure out the hidden number in $$$30$$$ queries. We can do by doing the following steps:-
- First we query "? $$$0$$$" to find the number of set bits in the hidden number.
- For every bit from $$$1st$$$ bit to $$$29th$$$ bit from right we can query a number with $$$ith$$$ bit set to find whether it was set in the hidden number or not, while accounting for the fact that this operation would flip the $$$ith$$$ bit.
- Now we want to find the state $$$30th$$$ bit which can we can infer from the initial count of set bits and the count we found during $$$29$$$ queries in $$$2nd$$$ step.
After these $$$30$$$ queries we will be able to construct the current hidden number $$$x$$$ and just query "? $$$x⊕k$$$" to finally convert the hidden number to $$$k$$$.
Implementation
#include<stdio.h>
int main()
{
int t;
scanf("%d", &t);
while(t--) {
int k;
scanf("%d", &k);
int set_bits;
printf("? %d\n", 0);
fflush(stdout);
scanf("%d", &set_bits);
int set_bits_t = set_bits;
int set_bits_c{};
int p{};
for(int x = 0; x < 29; x++) {
printf("? %d\n", 1<<x);
fflush(stdout);
int temp;
scanf("%d", &temp);
if(temp == -1) {
return 0;
}
if(temp > set_bits) {
p = p|(1<<x);
}else {
set_bits_c++;
}
set_bits = temp;
}
if(set_bits_c != set_bits_t) {
p = p|(1<<29);
}
p = p^k;
printf("? %d\n", p);
fflush(stdout);
int temp;
scanf("%d", &temp);
if(temp == -1) {
return 0;
}
printf("!\n");
fflush(stdout);
}
return 0;
}




