[ UVA ] 10611- The Playboy Chimp

Author            : Anwar Jahid Ruman Hossain 
                    CSE, Batch - 6
                    BRUR.
Problem Statement : [ UVA ] 10611- The Playboy Chimp
Source            : URI Online Judge
Category          : Searching and Sorting
Algorithm         : Binary Search
Verdict           : Accepted
  1. #include<bits/stdc++.h>  
  2. using namespace std;  
  3. #define ll long long int  
  4. int searchUpper(int key,int arr[],int low,int high){  
  5.     int mid,value=-1;  
  6.     while(low<=high){  
  7.         mid=(low+high)/2;  
  8.         if(key>=arr[mid]){  
  9.             low=mid+1;  
  10.         }else{  
  11.             high=mid-1;  
  12.             value=arr[mid];  
  13.         }  
  14.   
  15.     }  
  16.     return value;  
  17. }  
  18. int searchDown(int key,int arr[],int low,int high){  
  19.     int mid,value=-1;  
  20.     while(low<=high){  
  21.         mid=(low+high)/2;  
  22.         if(key<=arr[mid]){  
  23.             high=mid-1;  
  24.         }else{  
  25.             value=arr[mid];  
  26.             low=mid+1;  
  27.         }  
  28.   
  29.     }  
  30.     return value;  
  31. }  
  32. int main(){  
  33.     //freopen("input.txt","r",stdin);  
  34.     //freopen("output.txt","w",stdout);  
  35.     int n,q;  
  36.     while(cin>>n){  
  37.         int arr[n];  
  38.         for(int i=0;i<n;i++){  
  39.             cin>>arr[i];  
  40.         }  
  41.         cin>>q;  
  42.         int index;  
  43.         for(int i=0;i<q;i++){  
  44.             cin>>index;  
  45.             int up=searchUpper(index,arr,0,n-1);  
  46.             int down=searchDown(index,arr,0,n-1);  
  47.             if(down==-1)cout<<"X "<<up<<endl;  
  48.             else if(up==-1)cout<<down<<" X"<<endl;  
  49.             else cout<<down<<" "<<up<<endl;  
  50.         }  
  51.     }  
  52.     return 0;  
  53. }  

No comments:

Post a Comment