-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathqueries-on-array.cpp
65 lines (54 loc) · 1.53 KB
/
queries-on-array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// CPP Program to solve queries on Left and Right
// Circular shift on array
#include <bits/stdc++.h>
using namespace std;
// Function to solve query of type 1 x.
void querytype1(int* toRotate, int times, int n)
{
// Decreasing the absolute rotation
(*toRotate) = ((*toRotate) - times) % n;
}
// Function to solve query of type 2 y.
void querytype2(int* toRotate, int times, int n)
{
// Increasing the absolute rotation.
(*toRotate) = ((*toRotate) + times) % n;
}
// Function to solve queries of type 3 l r.
void querytype3(int toRotate, int l, int r,
int preSum[], int n)
{
// Finding absolute l and r.
l = (l + toRotate + n) % n;
r = (r + toRotate + n) % n;
// if l is before r.
if (l <= r)
cout << (preSum[r + 1] - preSum[l]) << endl;
// If r is before l.
else
cout << (preSum[n] + preSum[r + 1] - preSum[l])
<< endl;
}
// Wrapper Function solve all queries.
void wrapper(int a[], int n)
{
int preSum[n + 1];
preSum[0] = 0;
// Finding Prefix sum
for (int i = 1; i <= n; i++)
preSum[i] = preSum[i - 1] + a[i - 1];
int toRotate = 0;
// Solving each query
querytype1(&toRotate, 3, n);
querytype3(toRotate, 0, 2, preSum, n);
querytype2(&toRotate, 1, n);
querytype3(toRotate, 1, 4, preSum, n);
}
// Driver Program
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof(a) / sizeof(a[0]);
wrapper(a, n);
return 0;
}