Skip to content

Commit 7cc250c

Browse files
authored
Add solution for B.S. Day 07 q1
Implement a solution to find pairs of integers within a specified sum range.
1 parent 5f31694 commit 7cc250c

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// https://codeforces.com/contest/1538/submission/356243914
2+
// Given an array of n integers,find all pairs (ai,aj): i<j where l≤ai+aj≤r
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
using ll = long long;
8+
#define all(x) (x).begin(), (x).end()
9+
10+
const int MOD = 1e9 + 7;
11+
const ll INF = 1e18;
12+
13+
void solve() {
14+
ll n,l,r;
15+
cin>>n>>l>>r;
16+
vector<ll> a(n);
17+
for(auto &x: a) cin>>x;
18+
//sort the array for Binary search
19+
sort(all(a));
20+
ll prs=0;
21+
//first find all pairs A with sum <= r then those pairs B with sum less than l
22+
for(int i=0;i<n;i++){
23+
int p =upper_bound(all(a),r-a[i])-a.begin();
24+
int q =upper_bound(all(a),l-1-a[i])-a.begin();
25+
prs+=p-1; prs-=q-1;
26+
if(a[i]+a[i]>=l && a[i]+a[i]<=r) prs--; //to remove self pair e.g. (ai,ai) absurd
27+
}
28+
//ans is (A-B)/2, divided by 2 to remove repeated pairs as order doesn't matter
29+
cout<<prs/2<<endl;
30+
}
31+
// T.C.: O(n*logn); S.C.: O(1)
32+
int main() {
33+
// Fast I/O
34+
ios::sync_with_stdio(false);
35+
cin.tie(nullptr);
36+
37+
int t;
38+
cin >> t;
39+
while (t--) {
40+
solve();
41+
}
42+
43+
return 0;
44+
}

0 commit comments

Comments
 (0)