题意:
交互题。
query l,r区间内第二大的数,要求得到整个数组最大的数。
思路:首先我们对整体数组进行query
找到第二大的数所在的位置,设这个位置为p。
然后分别对[1,p]和[p,n]进行query,看最大的数是在p的左端还是右端。
如果在左端,那我们二分左端的区间左端点,找到最右的左端点a满足[a,p]的query和[1,p]一致,此时得出答案是a。
在右端同理。
PS:这题二分细节有点多,有点坑。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int n;
int l ,r;
int ans = 0,ans1=0,ans2=0;
bool check(int x)
{
cout<<"? "<<ans<<" "<<x<<endl;
cout.flush();
int res = 0;
cin>>res;
if(res == ans)return 1;
else return 0;
}
bool check2(int x)
{
cout<<"? "<<x<<" "<<ans<<endl;
cout.flush();
int res = 0;
cin>>res;
if(res == ans)return 1;
else return 0;
}
int main()
{
cin>>n;
l = 1,r = n;
cout<<"? "<<l<<" "<<r<<endl;
cout.flush();
cin>>ans;
if(r-l<=1)
{
if(l==ans)
cout<<"! "<<r<<endl;
else cout<<"! "<<l<<endl;
return 0;
}
if(l==ans)goto ok1;
cout<<"? "<<l<<" "<<ans<<endl;
cout.flush();
cin>>ans1;
ok1:;
if(ans==r)goto ok2;
cout<<"? "<<ans<<" "<<r<<endl;
cout.flush();
cin>>ans2;
ok2:;
if(ans1==ans){
r = ans;
int ok = l;
while(l<r)
{
int mid = (l+r)/2;
if(mid==ans)break;
if(check2(mid))
{
ok = mid;
l = mid+1;
}
else{
r = mid;
}
}
cout<<"! "<<ok<<endl;
}
else
{
l = ans;
int ok = r;
while(l<r)
{
int mid = (l+r)/2;
if(mid==ans)break;
if(check(mid))
{
ok = mid;
r = mid;
}
else{
l = mid+1;
}
}
cout<<"! "<<ok<<endl;
}
}