Half the number of exercises 10 to find solution to a problem within a given range of numbers

Title Description

Now tell you a length \ (n \) of an ordered array of \ (A_1, A_2, ..., A_N \) , and \ (q \) once asked Always ask will give you two numbers \ (x_1 \) and \ (x_2 \) , for each inquiry, you need to determine the meet in the array \ (x_1 \ le a_i \ le x_2 \) elements (a_i \) \ number.

Input Format

Comprising a first line of input integer \ (n-(. 1 \ n-Le \ Le 100000) \) , for the number of elements in the array representation.
The second row contains the input \ (\ n-) integers, there is a space between each two of the elements in the array used to represent \ (a_1, a_2, ..., a_n (1 \ le a_i \ le 10 ^ 9 and A_1 \ Le A_2 \ Le ... \ Le A_N) \) .
The third line of the input contains an integer \ (Q (. 1 \ Le Q \ 100000 Le) \) , for indicating the number of interrogation.
Next \ (Q \) rows, each row comprising two integers \ (x_1, x_2 (. 1 \ Le x_1 \ Le x_2 \ Le ^ 10. 9) \) , indicates the number to be interrogated.

Output Format

For each query \ (x_1, x_2 \) , the output array satisfies \ (x_1 \ le a_i \ le x_2 \) elements \ (a_i \) number. Each output on separate lines.

Sample input

5
1 3 5 7 9
3
3 6
2 100
11 13

Sample Output

2
4
0

Topic analysis

This question is a bit of trouble at first glance, but in fact can also be used binary algorithm to solve.
But here we need to use the two-half each prompt \ (x_1, x_2 \) , we need to:

  • Found binary \ (\ le x_1 \) coordinates of the smallest element \ (i_1 \) ;
  • Dichotomous find \ (\ ge x_2 \) coordinates the largest element of \ (i_2 will be used \) .

So \ (i_2-i_1 + 1 \ ) is our answer.
Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, q, x1, x2, a[maxn];
int solve() {
    int L = 1, R = n, i1 = -1, i2 = -1;
    while (L <= R) {    // 查找>=x1的最小坐标i1
        int mid = (L + R) / 2;
        if (a[mid] >= x1) {
            i1 = mid;
            R = mid - 1;
        }
        else L = mid + 1;
    }
    L = 1; R = n;
    while (L <= R) {    // 查找<=x2的最大坐标i2
        int mid = (L + R) / 2;
        if (a[mid] <= x2) {
            i2 = mid;
            L = mid + 1;
        }
        else R = mid - 1;
    }
    if (i1 == -1 || i2 == -1) return 0;
    return i2 - i1 + 1;
}
int main() {
    cin >> n;
    for (int i = 1; i <= n; i ++) cin >> a[i];
    cin >> q;
    while (q --) {
        cin >> x1 >> x2;
        cout << solve() << endl;
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/zifeiynoip/p/11450641.html