Exercise 3-half solution to a problem to find the largest element less than x

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 a number \ (x \ ) , for Always ask, you need the output array \ (a \) is less than \ (x \) is the largest element.

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 contains an integer \ (X (. 1 \ Le X \ ^. 9 Le 10) \) , indicates the number to be interrogated.

Output Format

For each query (X \) \ , if the array (A \) \ is less than the present \ (X \) element of the output array \ (A \) is less than satisfying \ (X \) all elements of conditions in the largest element; otherwise output "-1." Each output on separate lines.

Sample input

5
3 5 7 9 11
3
2
9
15

Sample Output

-1
7
11

Topic analysis

This question relates to the algorithm: Two points.
The title ideas and previous question - "look than the minimum element x" - similar.
We also open in an initial or a \ (L =. 1 \) , to open a \ (= n-R & lt \) (left and right margins, respectively), to open a \ (RES = -1 \) (for recording is less than \ (X \) coordinates the largest number).
Loop condition \ (L \ le R \) enabled \ (MID = (L + R & lt) / 2 \) , and determines:

  • If \ (A [MID] \ X lt \) (the condition), the update \ (RES \) of \ (MID \) , while \ (L = MID. 1 + \) ;
  • Otherwise (the condition is not satisfied, i.e. \ (A [MID] \ GE X \) ), \ (R & lt MID = -. 1 \)

Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, a[maxn], q, x;

// solve函数用于返回大于等于x的最小元素
int solve(int x) {
    int L = 1, R = n, res = -1;
    while (L <= R) {
        int mid = (L + R) / 2;
        if (a[mid] < x) {
            res = mid;
            L = mid + 1;
        }
        else R = mid - 1;
    }
    if (res == -1) return -1; // 如果循环结束res==-1,说明没有找到答案
    return a[res];  // 因为res存的是最优解的坐标,所以返回a[res]
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i ++) cin >> a[i];
    cin >> q;
    while (q --) {
        cin >> x;
        cout << solve(x) << endl;
    }
    return 0;
}

Guess you like

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