题目
Obs: this is an interactive problem. More information is under the “Interaction” section.
MaratonIME is gathering to start another group practice. This time, Renzo decided to reward the students with candies as they solve problems. Curious as they are, the members of MaratonIME started to guess how many candies did Renzo bring. For each question, Renzo answered if the amount of candies was higher, lower or equal to the number asked.
Breno, noticing that the amount of candies could be very high, decided to limit the number of queries to 50. This way, the practice would start as soon as possible.
Renzo bought at least 1 and no more than 109 candies. Find how many candies were bought by Renzo with no more than 50 questions.
Input
For every question asked, read a character. It will be " > " if the amount of Renzo’s candies is higher than your guess, " < " if the amount of Renzo’s candies is lower than your guess or " = " if your guess is equal to the amount of Renzo’s candies.
Output
You must print every query in the format “Q y”, where y is the number guessed, and 1 ≤ y ≤ 1e9. After printing a question, you need to flush the output. Check the “Interaction” section for examples of how to flush the output.
Interaction
To ask Renzo a question, print the query in the format above. After printing a question, you need to flush the output. See examples below for each language:
C: fflush(stdout)
C++: cout.flush()
Java: System.out.flush()
Python: sys.stdout.flush()
Pascal: flush(output)
After each query, read a character as described above.
As soon as Renzo answers your question with “=” the program has to terminate. Your answer will be considered correct if you asked no more than 50 questions.
题目大意
猜数游戏
解题思路
由于这个数很大,不能一个一个数枚举。每次猜数都会反馈一个信息大于或小于。用可以用二分法处理这个问题,每次猜可能范围[l,r],的中间值,根据反馈的信息可以缩小可能的范围,每次都缩小为原来的二分之一,所以时间复杂度降为O(log2(n))
代码实现
#include <cstdio>
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int l=1,r=1e9;
while (l<=r)
{
char ch;
int mid=(l+r)/2;
printf("Q %d\n",mid);
cout.flush();
cin>>ch;
if (ch=='=') break;
if (ch=='>') l=mid+1;
if (ch=='<') r=mid-1;
}
}