Advertisement
Infernale

Menu

Jan 12th, 2019
453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int binarySearch(int arr[], int l, int r, int x){
  4.     if (r < l)
  5.         return -1;
  6.     int mid = l + (r - l) / 2;
  7.     if (arr[mid] == x)
  8.         return mid;
  9.     if (arr[mid] > x)
  10.         return binarySearch(arr, l, mid - 1, x);
  11.     return binarySearch(arr, mid + 1, r, x);
  12. }
  13.  
  14.  
  15. int count(int arr[], int n, int x){
  16.     int ind = binarySearch(arr, 0, n - 1, x);
  17.     if (ind == -1)
  18.         return 0;
  19.     int count = 1;
  20.     int left = ind - 1;
  21.     while (left >= 0 && arr[left] == x)
  22.         count++, left--;
  23.     int right = ind + 1;
  24.     while (right < n && arr[right] == x)
  25.         count++, right++;
  26.     return count;
  27. }  
  28.  
  29. int main(){
  30.     int size, queries, temp;
  31.     scanf("%d %d", &size, &queries);
  32.     int data[size];
  33.     for(int i=0;i<size;i++){
  34.         scanf("%d", &data[i]);
  35.     }
  36.     while(queries--){
  37.         scanf("%d", &temp);
  38.         printf("%d\n", count(data, size, temp));
  39.     }
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement