Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5f8725d

Browse files
DEEP BHATTACHARYYADEEP BHATTACHARYYA
DEEP BHATTACHARYYA
authored and
DEEP BHATTACHARYYA
committed
Add mergesort tree
1 parent 18d4ad0 commit 5f8725d

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

‎mergesort_tree.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
using namespace std;
4+
5+
vector<ll> a;
6+
7+
struct node {
8+
vector<ll> vec;
9+
node *left, *right;
10+
11+
node() {
12+
left = right = nullptr;
13+
}
14+
};
15+
16+
node* build(ll l, ll r) {
17+
node* newnode = new node();
18+
if (l == r) {
19+
newnode->vec.push_back(a[l]);
20+
return newnode;
21+
}
22+
ll m = l+(r-l)/2;
23+
newnode->left = build(l,m);
24+
newnode->right = build(m+1,r);
25+
ll i = 0, j = 0;
26+
vector<ll> &vec_l = newnode->left->vec, &vec_r = newnode->right->vec;;
27+
while (i < vec_l.size() and j < vec_r.size()) {
28+
if (vec_l[i] < vec_r[j]) {
29+
newnode->vec.push_back(vec_l[i]);
30+
i++;
31+
}
32+
else {
33+
newnode->vec.push_back(vec_r[j]);
34+
j++;
35+
}
36+
}
37+
38+
while (i < vec_l.size()) {
39+
newnode->vec.push_back(vec_l[i]);
40+
i++;
41+
}
42+
43+
while (j < vec_r.size()) {
44+
newnode->vec.push_back(vec_r[j]);
45+
j++;
46+
}
47+
48+
return newnode;
49+
}
50+
51+
// query to find number of elements less than k in [ql,qr]
52+
ll query(node* root, ll ql, ll qr, ll l, ll r, ll &k) {
53+
if (ql > r or qr < l or l > r) {
54+
return 0;
55+
}
56+
if (ql <= l and r <= qr) {
57+
return lower_bound(root->vec.begin(), root->vec.end(),k) - root->vec.begin();
58+
}
59+
ll m = l+(r-l)/2;
60+
return query(root->left, ql, qr, l, m, k) + query(root->right, ql, qr, m+1, r, k);
61+
}
62+
63+
int main() {
64+
ll i,n,k,q,l,r;
65+
cin >> n;
66+
a.resize(n);
67+
for (i = 0; i < n; i++) {
68+
cin >> a[i];
69+
}
70+
node* root = build(0,n-1);
71+
cin >> q;
72+
while (q--) {
73+
cin >> l >> r >> k;
74+
l--;r--;
75+
cout << query(root,l,r,0,n-1,k) << endl;
76+
}
77+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /