Skip to content

Commit 72eb691

Browse files
committed
Modified Day-01 Mathematics prefix sum solution
1 parent de89c4b commit 72eb691

1 file changed

Lines changed: 50 additions & 46 deletions

File tree

Lines changed: 50 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,73 @@
1-
#include <bits/stdc++.h>
2-
using namespace std;
3-
41
/*
52
Problem Statement:
6-
Given an array of integers and multiple range queries, find the sum
7-
of elements in a given range for each query.
3+
Some number of people (this number is even) are standing evenly in a circle.
4+
Each person looks directly at the person opposite to them.
5+
Given that person a is looking at person b, determine whom person c
6+
is looking at. If no such circle configuration exists, output -1.
87
9-
Approach (Using Prefix Sums):
10-
We construct a prefix sum array where prefix[i] stores the sum of
11-
elements from index 0 to i. For any range [l, r], the sum can be
12-
calculated in O(1) time using:
13-
prefix[r] - prefix[l - 1].
8+
Approach:
9+
1. The distance between opposites (diff) is half the total population.
10+
N = 2 * |a - b|
11+
2. Validity Check: a, b, and c must all be less than or equal to N.
12+
3. To find the opposite of c:
13+
- If c <= N/2, its opposite is c + N/2.
14+
- If c > N/2, its opposite is c - N/2.
1415
1516
Time Complexity:
16-
O(n + q)
17+
O(1) per test case
1718
1819
Space Complexity:
19-
O(n)
20-
20+
O(1)
2121
Example:
22-
Input:
23-
5
24-
1 2 3 4 5
25-
1
26-
1 3
27-
22+
7
23+
6 2 4
24+
2 3 1
25+
2 4 10
26+
5 3 4
27+
1 3 2
28+
2 5 4
29+
4 3 2
2830
Output:
29-
9
31+
8
32+
-1
33+
-1
34+
-1
35+
4
36+
1
37+
-1
3038
3139
Submission Link : https://codeforces.com/contest/1560/submission/355273828
3240
*/
3341

34-
int main() {
35-
int n;
36-
cin >> n;
37-
38-
vector<int> arr(n), prefix(n);
42+
#include <bits/stdc++.h>
43+
using namespace std;
3944

40-
// Building prefix sum array
41-
for (int i = 0; i < n; i++) {
42-
cin >> arr[i];
43-
if (i == 0) {
44-
prefix[i] = arr[i];
45-
} else {
46-
prefix[i] = prefix[i - 1] + arr[i];
47-
}
48-
}
45+
int main() {
46+
int t;
47+
cin >> t;
4948

50-
int q;
51-
cin >> q;
49+
while (t--) {
50+
long long a, b, c;
51+
cin >> a >> b >> c;
5252

53-
// Answering queries
54-
while (q--) {
55-
int l, r;
56-
cin >> l >> r;
53+
long long diff = llabs(a - b);
54+
long long N = 2 * diff;
5755

58-
int sum;
59-
if (l == 0) {
60-
sum = prefix[r];
56+
if (a > N || b > N || c > N) {
57+
cout << -1 << endl;
6158
} else {
62-
sum = prefix[r] - prefix[l - 1];
59+
long long half = N / 2;
60+
long long d;
61+
if (c <= half) {
62+
d = c + half;
63+
} else {
64+
d = c - half;
65+
}
66+
cout << d << endl;
6367
}
64-
65-
cout << sum << endl;
6668
}
6769

6870
return 0;
6971
}
72+
73+

0 commit comments

Comments
 (0)