File tree Expand file tree Collapse file tree
Problems/Binary-Search/Day-07/sol Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments