forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMo's Algorithm.cpp
87 lines (79 loc) · 1.33 KB
/
Mo's Algorithm.cpp
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
const int N=2e5+5;
const int M=1e6+5;
struct data
{
int l;
int r;
int idx;
long long store_ans;
};
int n, q, blocksz=1000;
int a[N];
data queries[N];
long long freq[M];
long long ans=0;
bool comp(data &d1, data &d2)
{
int blocka=d1.l/blocksz;
int blockb=d2.l/blocksz;
if(blocka<blockb)
return true;
else if(blocka==blockb)
return (d1.r<d2.r)^(blocka%2);
else
return false;
}
bool comp2(data &d1, data &d2)
{
return d1.idx<d2.idx;
}
void update(long long k, int sign) //Sign 1 = Add, -1 = Remove
{
if(sign==1)
{
ans-=freq[k]*freq[k]*k;
freq[k]++;
ans+=freq[k]*freq[k]*k;
}
else
{
ans-=freq[k]*freq[k]*k;
freq[k]--;
ans+=freq[k]*freq[k]*k;
}
}
void calcmo()
{
int moleft=1;
int moright=0;
for(int i=1;i<=q;i++)
{
int r=queries[i].r;
int l=queries[i].l;
while(moright<r)
{
moright++;
update(a[moright], 1);
}
while(moright>r)
{
update(a[moright], -1);
moright--;
}
while(moleft<l)
{
update(a[moleft], -1);
moleft++;
}
while(moleft>l)
{
moleft--;
update(a[moleft], 1);
}
queries[i].store_ans=ans;
}
}
//Problem 1: https://codeforces.com/contest/86/problem/D
//Solution 1: https://codeforces.com/contest/86/submission/45491857
//Problem 2 (Prefix Xor): https://codeforces.com/contest/617/problem/E
//Solution 2: https://codeforces.com/contest/617/submission/45491963