Advertisement
Andoroid

Untitled

Dec 9th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n,k;
  6. int a[100000];
  7. int b[100000];
  8.  
  9. int binarySearch(int l, int r, int x)
  10. {
  11. if (r >= l) {
  12. int mid = l + (r - l) / 2;
  13.  
  14. if (a[mid] == x)
  15. return mid;
  16.  
  17. if (a[mid] > x)
  18. return binarySearch(l, mid - 1, x);
  19. return binarySearch(mid + 1, r, x);
  20. }
  21.  
  22. return -1;
  23. }
  24.  
  25. int main() {
  26. n = 20;
  27. k = 5;
  28. for (int i = 0; i < n; i++) a[i] = rand() % 10;
  29. for (int i = 0; i < k; i++) b[i] = rand() % 15;
  30. cout << "Первый массив" << "\n";
  31. for (int i = 0; i < n; i++) cout << a[i] << " ";
  32. cout << "\n";
  33. sort(a, a + n);
  34. cout << "Отсортированый первый массив" << "\n";
  35. for (int i = 0; i < n; i++) cout << a[i] << " ";
  36. cout << "\n";
  37. cout << "Второй массив массив" << "\n";
  38. for (int i = 0; i < k; i++) cout << b[i] << " ";
  39. cout << "\n";
  40. for (int i = 0; i < k; i++) {
  41. int c = b[i];
  42. int p = binarySearch(0, n - 1, c);
  43. if (p == -1) {
  44. cout << "0" << "\n";
  45. }
  46. int startP = p;
  47. while (a[p - 1] == c && p >= 1) p--;
  48. cout << p + 1 << " ";
  49. p = startP;
  50. while (a[p + 1] == c && p < n - 1) p++;
  51. cout << p + 1 << "\n";
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement