Day 3 C2. Guessing the Greatest (hard version)

这是一个交互式的编程问题,目标是在不超过20次查询的情况下找出数组a中最大元素的下标。通过询问子数组的第二最大元素的下标,逐步缩小范围。二分法在此问题中被用来有效减少查询次数。
摘要由CSDN通过智能技术生成

Problem:
The only difference between the easy and the hard version is the limit to the number of queries.
This is an interactive problem.
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 20 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 20 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

Example
input
5
3
4

output
? 1 5
? 4 5
! 1

Note
In the sample suppose a is [5,1,4,2,3]. So after asking the [1…5] subsegment 4 is second to max value, and it’s position is 3. After asking the [

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值