Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <conio.h>
  3.  
  4. int main()
  5. {
  6. long n,m,i,key,leftRes=-1,rightRes=-1,first,last;
  7. long arr[100000];
  8. int mid;
  9. //freopen("input.txt", "r", stdin);
  10. //freopen("output.txt", "w", stdout);
  11. freopen("binsearch.in","r",stdin);
  12. freopen("binsearch.out","w",stdout);
  13. scanf("%i",&n);
  14. for(i=0; i<n; i++)
  15. scanf("%i",&arr[i]);
  16. scanf("%i",&m);
  17. for(i=0; i<m; i++)
  18. {
  19. scanf("%i",&key);
  20. first = 0;
  21. last = n-1;
  22. if (key<arr[first] || key>arr[last])
  23. {
  24. printf("-1 -1\n");
  25. }
  26. else
  27. {
  28. while (first < last)
  29. {
  30. mid = (first+last)/2;
  31. if (key <= arr[mid]) last = mid;
  32. else first = mid+1;
  33. }
  34. if ( arr[last] == key )
  35. {
  36.  
  37. leftRes=last;
  38. while((leftRes>0)&&(arr[leftRes-1] == key)) leftRes--;
  39. rightRes=last;
  40. while((rightRes<n-1)&&(arr[rightRes+1] == key)) rightRes++;
  41. printf("%i %i\n",leftRes+1,rightRes+1);
  42. }
  43. else
  44. printf("-1 -1\n");
  45. }
  46. }
  47. return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement