fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. ll int findDiff(ll int x,ll int arr[],ll int n);
  5.  
  6. int main()
  7. {
  8. ios_base::sync_with_stdio(false);
  9. cout.tie(NULL);
  10. cin.tie(NULL);
  11. ll int n,q;
  12.  
  13. cin>>n>>q;
  14. ll int arr[n],que[q],b[q];
  15. for(ll int i=0;i<n;i++) cin>>arr[i];
  16. for(ll int i=0;i<q;i++)
  17. {
  18. cin>>que[i];
  19. b[i]=findDiff(que[i],arr,n);
  20. }
  21. //memset(b, -1, sizeof(b));
  22.  
  23. for(ll int x:b)
  24. cout<<x<<endl;
  25. return 0;
  26. }
  27.  
  28. ll int findDiff(ll int x,ll int arr[],ll int n)
  29. {
  30. ll int p,r;
  31. ll int just_greater=INT_MAX,just_smaller=INT_MIN;
  32. for(ll int i=0;i<n;i++)
  33. {
  34. if(arr[i] > x and arr[i] < just_greater)
  35. just_greater = arr[i];
  36. if(arr[i] < x and just_smaller < arr[i])
  37. just_smaller = arr[i];
  38.  
  39. }
  40. if(just_greater != INT_MAX)
  41. p=just_greater;
  42. else
  43. p=-1;
  44.  
  45. if(just_smaller !=INT_MIN)
  46. r=just_smaller;
  47. else
  48. r=-1;
  49. int anss;
  50. if(p>=0 && r>=0)
  51. {
  52. anss=p-r;
  53. }
  54. else
  55. anss=-1;
  56.  
  57. return anss;
  58. }
  59.  
  60.  
  61.  
  62.  
Success #stdin #stdout 0s 4304KB
stdin
7 7
2 2 5 6 8 8 12
1
2
3
6
8
12
15
stdout
-1
-1
3
3
6
-1
-1