题:
This is an interactive problem.
Homer likes arrays a lot and he wants to play a game with you.
Homer has hidden from you a permutation a1,a2,…,an of integers 1 to n. You are asked to find any index k (1≤k≤n) which is a local minimum.
For an array a1,a2,…,an, an index i (1≤i≤n) is said to be a local minimum if ai<min{ai?1,ai+1}, where a0=an+1=+∞. An array is said to be a permutation of integers 1 to n, if it contains all integers from 1 to n exactly once.
Initially, you are only given the value of n without any other information about this permutation.
At each interactive step, you are allowed to choose any i (1≤i≤n) and make a query with it. As a response, you will be given the value of ai.
You are asked to find any index k which is a local minimum after at most 100 queries.
Interaction
You begin the interaction by reading an integer n (1≤n≤10?) on a separate line.
To make a query on index i (1≤i≤n), you should output “? i” in a separate line. Then read the value of ai in a separate line. The number of the “?” queries is limited within 100.
When you find an index k (1≤k≤n) which is a local minimum, output “! k” in a separate line and terminate your program.
In case your query format is invalid, or you have made more than 100 “?” queries, you will receive Wrong Answer verdict.
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.
Hack Format
The first line of the hack should contain a single integer n (1≤n≤10?).
The second line should contain n distinct integers a1,a2,…,an (1≤ai≤n).
input
5
3
2
1
4
5
output
? 1
? 2
? 3
? 4
? 5
! 3
Note
In the example, the first line contains an integer 5 indicating 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.
题意:
输入一个数组的长度为n(1≤n≤10?)。
你可以查询最多100个位置的数,输出“? x”,其中x为查询的位置索引,然后再输入数组的该位置索引处的数值。
经过查询之后输出任意一个数 ai < min{ ai?1,ai+1} 的位置。
(可以重复查询)
思路:
因为(1≤n≤10?),但是最多可以查询100个位置的数,所以应该用二分法。
注意:
交互题要使用题目中给出的特定的输出方式!
C++中的“ endl ”可以插入换行符并刷新输出流。其中刷新输出流指的是将缓冲区的数据全部传递到输出设备并将输出缓冲区清空。
所以如果每个输出后面加了endl就可以不用fflush(stdout) or cout.flush() in C++;
#include<cstdio>
using namespace std;int a[100005];int main()
{
int t;scanf("%d",&t);a[0]=100005;a[t+1]=100005;int mid,l=1,r=t;while(l<r){
mid=(l+r+1)>>1; //“>>1”是位运算,意思是括号括起来的数的二进制往右移一位,即除以2//“>>2”意思是往右移两位,即除以4//位运算的速度会快很多,可优先选择使用printf("? %d\n",mid),fflush(stdout);scanf("%d",&a[mid]);printf("? %d\n",mid-1),fflush(stdout);scanf("%d",&a[mid-1]);if(a[mid]<a[mid-1]){
l=mid;}else{
r=mid-1;}}printf("! %d\n",l);fflush(stdout); return 0;}