CF1480 C Searching Local Minimum

Searching Local Minimum

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 index i (1≤i≤n) is said to be a local minimum if ai<min{ai1,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 nn 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 kk which is a local minimum after at most 100 queries.

Interaction

You begin the interaction by reading an integer nn (1≤n≤105) 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 aiai 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 nn (1≤n≤105).

The second line should contain nn distinct integers a1,a2,…,an (1≤ai≤n).

 

思路

明显的二分查找题,唯一的独特之处就是程序要与测评机互动,掌握了正确方法就没什么大问题。

代码

 1 #include<cstdio>
 2 using namespace std;
 3 int a[100010];
 4 int n;
 5 void ask(int p)
 6 {
 7     if (1 <= p && p <= n)
 8     {
 9         printf("? %d\n", p);
10         fflush(stdout);
11         scanf("%d", &a[p]);
12     }
13 }
14 int main()
15 {
16     scanf("%d", &n);
17     int l = 1, r = n;
18     int mid;
19     while (l < r)
20     {
21         mid = (l + r) / 2;
22         ask(mid);
23         ask(mid + 1);
24         if (a[mid] < a[mid + 1])
25             r = mid;
26         else
27             l = mid + 1;
28     }
29     printf("! %d\n", l);
30     fflush(stdout);
31     return 0;
32 }

 

上一篇:再讲mysql 5.7的组提交&发现疑似代码缺陷


下一篇:eclipse JVM 性能调优