Input
5
3
2
1
4
5
Output
? 1
? 2
? 3
? 4
? 5
! 3
Note
In the example, the first line contains an integer 5indicating that the length of the array is n=5
The example makes five “?” queries, after which we conclude that the array is a=[3,2,1,4,5]and k=3 is local minimum.
思路
这题的关键在于对局部最小值含义的理解,题目中表述为 a[i]<min{a[i−1],a[i+1]},即a[i-1]>a[i],a[i]<a[i+1]。此时若我们将其变化为a[l-1]>a[l],a[r]<a[r+1],不难看出当l==r时便可得出结果。由于a[0]与a[n+1]视作无穷大,所以我们首先可以将1-n区间视为合法,然后若a[mid]<a[mid+1],则可知l-mid区间符合要求,否则可知mid+1-r区间符合要求。
代码
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9+7;
const int maxn=1e6+5;
typedef long long ll;
const int inf=1e9;
int n,a[maxn];
void query(int x)
{
cout<<"? "<<x<<endl;
fflush(stdout);
cin>>a[x];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n;
query(1);
query(n);
int l=1,r=n;
while(l<r)
{
int mid=(l+r)/2;
query(mid);
query((mid+1));
if(a[mid]<a[mid+1])
r=mid;
else
l=mid+1;
}
cout<<"! "<<r<<"\n";
return 0;
}