CF 600B
Title: Given N,m, array a (n number), array b (number of M), for each of the elements in the array B, the number of arrays A is less than or equal to the array of that element.
Problem-Solving ideas: Sorting array A, and then b[i for each element], the result of finding the first place in array a with a value greater than b[i]
/*CF 600B Queries about less or equal elements---binary search*/#include<cstdio>#include<algorithm>using namespacestd;Const intMAXN =200005;intA[MAXN], B[MAXN];/*@function: Finds the first position greater than key in array A's interval [x, y) @param1: A array name to find @param2: [x, Y) indicates left closed right open interval @param3: Lookup value @ Return: Returns the first position greater than key*/intBinarySearch (int*a,intXintYintkey) { while(X <y) { intMID = x + (y-x)/2; if(A[mid] <=key) {x= Mid +1; } Else{y=mid; } }//While (x<y) returnx;}intMain () {intN, M; //n Array a length, M array b element number while(SCANF ("%d%d", &n, &m) = =2){ for(inti =0; I < n; ++i) {scanf ("%d", A +i); }//For (i) for(inti =0; I < m; ++i) {scanf ("%d", B +i); }//For (i)Sort (A, A +N); A[n]=1<< -; //for each number in B b[i], find the number of numbers less than or equal to B[i] in a for(inti =0; I < m; ++i) { intK = BinarySearch (A,0, N, B[i]); printf (i= = M-1?"%d\n":"%d", K); }//For (i) } return 0;}
View Code
You can also make direct use of the Upper_bound in the STL to greatly simplify the code:
/*CF 600B Queries about less or equal elements---binary search*/#include<cstdio>#include<algorithm>using namespacestd;Const intMAXN =200005;intA[MAXN];intB[MAXN];intMain () {intN, M; while(SCANF ("%d%d", &n, &m) = =2){ for(inti =0; I < n; ++i) {scanf ("%d", A +i); }//For (i)Sort (A, A +N); for(inti =0; I < m; ++i) {scanf ("%d", B +i); intK = (Upper_bound (A, a + N, B[i])-a); printf (i= = M-1?"%d\n":"%d", K); }//For (i) } return 0;}
View Code
CF 600B Queries about less or equal elements---binary search