题目链接、
题意:
交互题,每次询问? x y
读入x,说明x%a>=y%a
否则读入y,
60次以内将a猜出来
输入有多组,start表示新一组游戏的开始,end表示结束程序
解:
考虑二进制,枚举最高位,然后从依次向下枚举低位,得到%a情况下的最大值ans,即ans=a-1,输出ans+1即可
奇怪的是,我一开始写的是x,y,一直死在第一个上,改成y,x,就过了,可能是等号的问题
是边界问题、当输出1,0的时候一定是返回x,是我疏忽了
详细点解释吧,首先x%a 肯定在 0到a-1范围内,这题要考虑的就是找到a-1,然后+1就是答案了
一个数转化为二进制来看,
枚举最高位的1,也就是说在0到a-1范围内找到最大的10000(二进制,k个0,也就是2^k,0<=k<30)
将ans记为2^k,为了看的形象点暂时写作二进制形式100000(k个0)
然后向下枚举低位的1,输出 ? 110000 100000(ans+2^(k-1)和ans),如果输出x,就说明ans+2^(k-1)在0到a-1范围内,
ans = ans+2^(k-1),接着枚举下一位k-2,最后的ans就是a-1,那么输出ans+1即可
举个例子,假设a = 31(2^5-1)
那么是这样的(这里是第二份代码的模拟)
? 0 1
y
? 1 2
y
? 2 4
y
? 4 8
y
? 8 16
y
? 16 32
x---------------------------16%31 = 16, 32%31 = 1,此时ans = 2^4 = 16
? 24 16
x----------------------------ans = 16+8 = 24
? 28 24
x----------------------------ans = 24+4 = 28
? 30 28
x----------------------------ans = 28+2 = 30
? 31 30
y----------------------------31%31 = 0, 30 %31 = 30
所以ans = 30,输出ans+1 = 31
另一个例子,假设 a = 1,这就是我之前错的地方、如果是? 1 0 的话无论如何都是x,那就错了
? 0 1
y-------------------0%1 = 0, 1%1 = 0
ans = 0,输出1
稍微说一句为什么枚举2^k可以,
你想,如果2^k在a-1范围内,2^(k+1)不在
假设2^k = 100,那么2^(k+1) = 1000
那么a肯定在101到111之间,那么1000 %a后一定就小于100(1000 = 2*100),所以这样就可以了
代码、
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+7;
void solve(){
char op[10];
int ans = 0,pos = 0;
for(int i=0;i<=30;i++){
int x = 1<<i,y = i==0?0:1<<(i-1);
cout<<"? "<<y<<" "<<x<<endl;
fflush(stdout);
cin>>op;
if(op[0] == 'x'){pos = i-1;break;}
}
if(pos != -1){
ans = 1<<pos;
for(int i = pos-1;~i;i--){
int x = 1<<i;
cout<<"? "<<ans<<" "<<ans+x<<endl;
fflush(stdout);
scanf("%s",op);
if(op[0] == 'y')ans+=1<<i;
}
}
cout<<"! "<<ans+1<<endl;
}
int main(){
char p[100];
while(cin>>p&&p[0]!='e')solve();
return 0;
}
另,有了endl好像就不用fflush了,但是用scanf和printf的话加fflush也不对,就很萌
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+7;
void solve(){
char op[10];
int ans = 0,pos = 0;
for(int i=0;i<=30;i++){
int x = 1<<i,y = i==0?0:1<<(i-1);
cout<<"? "<<y<<" "<<x<<endl;
cin>>op;
if(op[0] == 'x'){pos = i-1;break;}
}
if(pos != -1){
ans = 1<<pos;
for(int i = pos-1;~i;i--){
int x = 1<<i;
cout<<"? "<<ans+x<<" "<<ans<<endl;
cin>>op;
if(op[0] == 'x')ans+=1<<i;
}
}
cout<<"! "<<ans+1<<endl;
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
char p[100];
while(cin>>p&&p[0]!='e')solve();
return 0;
}