题目链接:https://codeforces.com/contest/1486/problem/C1
There is an array a of n different numbers. In one query you can ask the position of the second maximum element in a subsegment a[l…r]. Find the position of the maximum element in the array in no more than 40 queries.
A subsegment a[l…r] is all the elements al,al+1,…,ar. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.
Input
The first line contains a single integer n (2≤n≤105) — the number of elements in the array.
Interaction
You can ask queries by printing “? l r” (1≤l<r≤n). The answer is the index of the second maximum of all elements al,al+1,…,ar. Array a is fixed beforehand and can’t be changed in time of interaction.
You can output the answer by printing “! p”, where p is the index of the maximum element in the array.
You can ask no more than 40 queries. Printing the answer doesn’t count as a query.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
fflush(stdout) or cout.flush() in C++;
System.out.flush() in Java;
flush(output) in Pascal;
stdout.flush() in Python;
see documentation for other languages
Hacks
To make a hack, use the following test format.
In the first line output a single integer n (2≤n≤105). In the second line output a permutation of n integers 1 to n. The position of n in the permutation is the position of the maximum
分析
第一次找 1 到 n 的区间找到第二大的位置 x ,然后即可判断出最大值的位置:如果 1 到 x 区间第二小还是位置 x ,那么最大值的位置就在 1 到 x-1 中。
知道最大值的位置区间,再二分即可。
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int er1(int l,int r,int x)
{
if(l == r) return l;
int y,ans = 1e9;
while(l <= r)
{
int mid = (l + r) >> 1;
cout<<"? "<<x<<" "<<mid<<endl;
cin>>y;
if(x == y) r = mid - 1, ans = min(ans, mid);
else l = mid + 1;
}
return ans;
}
int er2(int l,int r,int x)
{
if(l == r) return l;
int y,ans = 0;
while(l <= r)
{
int mid = (l + r) >> 1;
cout<<"? "<<mid<<" "<<x<<endl;
cin>>y;
if(x == y) l = mid + 1, ans = max(ans, mid);
else r = mid - 1;
}
return ans;
}
void ask(int l,int r)
{
int x,y,ans;
cout<<"? "<<l<<" "<<r<<endl;
cin>>x;
if(x > l)
{
cout<<"? "<<l<<" "<<x<<endl;
cin>>y;
if(x == y) ans = er2(l, x - 1, x);
else ans = er1(x + 1, r, x);
}
else
{
ans = er1(x + 1, r, x);
}
cout<<"! "<<ans<<endl;
}
int main() {
int n;
cin>>n;
ask(1, n);
return 0;
}