File tree Expand file tree Collapse file tree
Problems/Binary-Search/Day-07/sol/BEESA-MANISH Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+
2+ /*
3+
4+ Submission link: https://codeforces.com/contest/1538/submission/356096805
5+
6+ TC - O(N \log N)
7+ SC - O(N)
8+
9+ Approach :
10+ Sort the numbers first so they are in increasing order. This makes searching easier.
11+ Take one number and look for another number after it such that their sum lies between l and r.
12+ Find the range of numbers that can be added to the current number to stay within l and r.
13+ Count how many numbers fall in that range and add this count to the answer.
14+
15+ */
16+
17+ #include < iostream>
18+ #include < vector>
19+ #include < algorithm>
20+
21+ using namespace std ;
22+ long long countPairsUnder (const vector<int >& a, int limit) {
23+ long long count = 0 ;
24+ int left = 0 ;
25+ int right = a.size () - 1 ;
26+ while (left < right) {
27+ if (a[left] + a[right] <= limit) {
28+ count += (right - left);
29+ left++;
30+ } else {
31+ right--;
32+ }
33+ }
34+ return count;
35+ }
36+
37+ void solve () {
38+ int n, l, r;
39+ cin >> n >> l >> r;
40+ vector<int > a (n);
41+ for (int i = 0 ; i < n; i++) {
42+ cin >> a[i];
43+ }
44+ sort (a.begin (), a.end ());
45+ long long result = countPairsUnder (a, r) - countPairsUnder (a, l - 1 );
46+ cout << result << " \n " ;
47+ }
48+
49+ int main () {
50+ int t;
51+ cin >> t;
52+ while (t--) {
53+ solve ();
54+ }
55+ return 0 ;
56+ }
You can’t perform that action at this time.
0 commit comments