Skip to content

Commit 8131cf8

Browse files
authored
Merge pull request #439 from Aaryan-Degama/main
d7q1
2 parents 2e556db + f76c687 commit 8131cf8

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
//link : https://codeforces.com/problemset/submission/1538/356089286
2+
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
#define fastio ios::sync_with_stdio(false); cin.tie(NULL);
8+
9+
using ll = long long;
10+
using vi = vector<ll>;
11+
12+
void solve() {
13+
int n;
14+
ll l, r;
15+
cin >> n >> l >> r;
16+
17+
vi a(n);
18+
for (int i = 0; i < n; i++) {
19+
cin >> a[i];
20+
}
21+
22+
sort(a.begin(), a.end());
23+
24+
ll ans = 0;
25+
26+
for (int i = 0; i < n; i++) {
27+
ll low = l - a[i];
28+
ll high = r - a[i];
29+
30+
int left = lower_bound(a.begin() + i + 1, a.end(), low) - a.begin();
31+
int right = upper_bound(a.begin() + i + 1, a.end(), high) - a.begin();
32+
33+
ans += max(0, right - left);
34+
}
35+
36+
cout << ans << '\n';
37+
}
38+
39+
int main() {
40+
fastio
41+
42+
int t;
43+
cin >> t;
44+
while (t--) {
45+
solve();
46+
}
47+
48+
return 0;
49+
}
50+
51+
52+
53+
/*
54+
55+
Explaination:
56+
1. Sort the array.
57+
2. For each index i, we want to count indices j > i such that:
58+
l ≤ a[i] + a[j] ≤ r
59+
This can be rewritten as:
60+
l - a[i] ≤ a[j] ≤ r - a[i]
61+
3. Since the array is sorted, use binary search:
62+
- lower_bound to find the first j where a[j] ≥ (l - a[i])
63+
- upper_bound to find the first j where a[j] > (r - a[i])
64+
4. The number of valid pairs for index i is (right - left).
65+
5. Sum this for all i.
66+
67+
Complexity:
68+
- Time complexity: O(n log n)
69+
- Space complexity: O(n)
70+
71+
*/

0 commit comments

Comments
 (0)