Sunday, 5 February 2017

Circular Array Rotation

John Watson performs an operation called a right circular rotation on an array of integers, . After performing one right circular rotation operation, the array is transformed from  to .
Watson performs this operation  times. To test Sherlock's ability to identify the current element at a particular position in the rotated array, Watson asks  queries, where each query consists of a single integer, , for which you must print the element at index  in the rotated array (i.e., the value of ).
Input Format
The first line contains  space-separated integers, , and , respectively. 
The second line contains  space-separated integers, where each integer  describes array element  (where ). 
Each of the  subsequent lines contains a single integer denoting .
Constraints
Output Format
For each query, print the value of the element at index  of the rotated array on a new line.
Sample Input
3 2 3
1 2 3
0
1
2
Sample Output
2
3
1
Explanation
After the first rotation, the array becomes 
After the second (and final) rotation, the array becomes .
Let's refer to the array's final state as array . For each query, we just have to print the value of  on a new line:
  1. , so we print  on a new line.
  2. , so we print  on a new line.
  3. , so we print  on a new line.
Solution:-

#include <iostream>
using namespace std;
int main() 
{
   int n,k,q,m,j;
   cin>>n>>k>>q;
   k%=n;                       
   int *A= new int[n] ;                       
   for(int i=0;i<n;i++) 
   cin>>A[i];                         
   for(int i=0;i<q;i++)
   {
     cin>>m;                                
  
    j=m-k;
     if(j<0) 
       cout<<A[n+j]<<endl;         
     else 
      cout<<A[j]<<endl;                    
    }
 return 0;
}
Share:

0 comments:

Post a Comment