Codeforces Round #700 (Div. 2)C. Searching Local Minimum(交互+二分)

题目链接

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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值