-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqrt_decomp_mo.sublime-snippet
87 lines (80 loc) · 1.71 KB
/
sqrt_decomp_mo.sublime-snippet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<snippet>
<content><![CDATA[
// mos algorithm for calculating distinct elements in given range
// frequency array
lint hash1[1000005];
// block size
lint blk=1;
// query structure
struct query{
lint l;
lint r;
lint idx;
};
// optimised sorting for mos algo
// odd even variations
bool compare(query p,query q)
{
if(p.l/blk!=q.l/blk)
return p.l<q.l;
return (p.l/blk&1)?(p.r<q.r):(p.r>q.r);
}
void add(lint &c,vector<lint> &arr,lint pos)
{
if(hash1[arr[pos]]==0)
c++;
hash1[arr[pos]]++;
}
void del(lint &c,vector<lint> &arr,lint pos)
{
hash1[arr[pos]]--;
if(hash1[arr[pos]]==0)
c--;
}
lint get(lint c,vector<lint> &arr)
{
return c;
}
// offline queries without updates
// O((n+q)*sqrt(n)*f), where f is complexity of operations of ds
// Q array should contain 0 based indexing queries
vector<lint> mos_algo(vector<query> Q,vector<lint> arr)
{
blk=high(sqrt(arr.size()),1.00);
sort(Q.begin(),Q.end(),compare);
vector<lint> ans(Q.size());
lint c=0; // mantain required ds
lint l=0;
lint r=-1;
for(query q:Q)
{
while(l>q.l)
{
l--;
add(c,arr,l);
}
while(r<q.r)
{
r++;
add(c,arr,r);
}
while(l<q.l)
{
del(c,arr,l);
l++;
}
while(r>q.r)
{
del(c,arr,r);
r--;
}
ans[q.idx]=get(c,arr);
}
return ans;
}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>sqrt_decomp_mo</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>