#P8481. 「HGOI-1」Binary search
「HGOI-1」Binary search
Background
is learning binary search.
Problem Description
As everyone knows, when computing in binary search, you can use or . So the student , who cannot decide between the two, added randomization to their binary search code: each time, they randomly choose one of them as .
Note that choosing different mid will also affect other parameters. Please follow the code.
Now gives you the sequence used in the binary search (guaranteed to be strictly increasing) and the number they want to find (guaranteed to be in the sequence). They want to know, in the best possible luck, how many iterations the loop needs to run (i.e., the minimum possible final value of in the code).
Loop:
int find(int *num,int x,int len)
{
int l=0,r=len-1,mid,cnt=0,w;
while(l<r)
{
cnt++;
w=rand()%2;
mid=(l+r+w)/2;
if(num[mid]-w<x) l=mid+!w;
else r=mid-w;
}
return mid;
}
Recursion:
int cnt;
int get(int *num,int x,int l,int r)
{
if(l==r) return l;
cnt++;
int w=rand()%2;
int mid=(l+r+w)/2;
if(num[mid]-w<x) return get(num,x,mid+!w,r);
else return get(num,x,l,mid-w);
}
int find(int *num,int x,int len)
{
cnt=0;
return get(num,x,0,len-1);
}
Note: The two pieces of code above are completely equivalent.
Here is a further explanation of the role of in the code above.
For example, for the interval , there are elements. Although the value of changes with the value of , the final chosen interval must be either or . You can simulate it yourself using the code above.
For the interval , there are elements. The value of is independent of , but the values of and will be affected by . The final chosen interval may be , () or , ().
Input Format
The first line contains an integer , the length of the sequence.
The second line contains strictly increasing integers, the sequence of .
The third line contains an integer , the number of queries.
The next lines each contain an integer, the number to query.
Output Format
For each query, output an integer representing the minimum number of loop iterations.
10
1 2 4 6 7 8 10 13 15 17
3
4
10
15
3
3
3
13
1 2 4 6 10 12 19 23 45 99 101 123 134
5
1
2
10
19
123
3
4
3
3
4
Hint
Sample 1 Explanation
Find :
Take .
Take .
Take (exit the loop).
Sample 2 Explanation
Query the position of .
$$[1,13] \stackrel{w=0}{\longrightarrow} [1,7]\stackrel{w=0}{\longrightarrow}[5,7] \stackrel{w=1}{\longrightarrow} [5,5]$$Constraints and Notes
This problem uses bundled tests. There are in total, and the final score is the sum of the scores of all .
$$\def\arraystretch{1.5} \begin{array}{|c|c|c|}\hline \textbf{Task} & \textbf{Score} & \text{Special Limits} \cr\hline 1 & 25 & n \le 20 \cr\hline 2 & 35 & n=2^k(k \in \mathbf{N}) \cr\hline 3 & 40 & \cr\hline \end{array}$$For of the testdata, it is guaranteed that , , .
This problem has an extra sub.
Translated by ChatGPT 5