Number range - two-thirds

Sample input:

6 3
1 2 2 3 3 4
3
4
5

Sample output:

3 4
5 5
-1 -1
#include <iostream>
using namespace std;
const int N = 100010;
int a[N];
int main()
{
    int n,q,x;
    cin>>n>>q;
    for(int i = 0;i<n;i++) cin>>a[i];
    while(q--)
    {
        cin>>x;
        int l = 0, r = n - 1;
        while(l < r)
        {
            int mid = (l + r) >> 1;
            if(a[mid] >= x) r = mid;
            else l = mid + 1;
        }
        if(a[l] != x) cout<<"-1 -1"<<endl;
        else{
            cout<<l<<' ';
            
            l = 0, r = n - 1;
            while(l < r)
            {
                int mid = (l + r + 1) >> 1;
                if(a[mid] <= x) l = mid;
                else r = mid - 1;
            }
            cout<<l<<endl;
        }
    }
    
}

We sample here as example:

Value: 122334

Number: 012345

It can be considered in the following situations

1)a[mid] >= x,那么 r =  mid; else l = mid + 1;

2)a[mid] <= x,那么 l = mid; else r = mid - 1;

While mid there are two possibilities:

1、mid = l + r >> 1;

2、mid = l + r + 1 >> 1;

Two or more combinations of two, four cases can be drawn.

一)mid = l + r >> 1; a[mid] >= x,那么 r =  mid; else l = mid + 1;

This is the case of a positive solution of the resulting answer is the position of the digital began to appear, this time can be obtained q [l] and q [r] The analog solutions are positive. It is determined by a [l] == x; cout << l << endl or a [r] == x; cout << r << endl; this should be kept to the left boundary shrinkage, the final r and l i.e., the starting point is a position overlapping the position x.

Two) mid = l + r >> 1; a [mid] <= x, then l = mid; else r = mid - 1; contraction at this time is kept to the right. This time by simulating a sample, we will find an infinite loop

Three) mid = l + r + 1 >> 1; a [mid] <= x, then l = mid; else r = mid - 1; this will not dead cycle time, i.e., is kept to give the Right contraction.

Four) mid = l + r + 1 >> 1; a [mid]> = x, then r = mid; else l = mid + 1; not the end of this time the number obtained, but the starting position.

By the above, if you want to find the starting position number, then the left will keep shrinking, r = mid; contrary, if the number of the end position Looking, shrinkage will have the right, l = mid; will be noted that the left divisible received, and then divided by 2 so +1.

Guess you like

Origin www.cnblogs.com/longxue1991/p/12635005.html