-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmo_algo_1.cpp
80 lines (80 loc) · 1.52 KB
/
mo_algo_1.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
#include<bits/stdc++.h>
using namespace std;
#define int long long int
#define SYNC std::ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
#define FRE freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
typedef vector<int> vi;
#define pb push_back
#define all(v) (v).begin(),(v).end()
#define sz(a) (int)((a).size())
#define sq(x) ((x)*(x))
const int N = 2e5+5;
int n, block = 555;
int cnt[(int)2e6+1],ans;
int a[N];
struct pt
{
int l;
int r;
int id;
};
bool comp(pt &x, pt &y)
{
// Sorting via sqrt decomposition
if(x.l/block != y.l/block) return x.l/block < y.l/block;
return x.r < y.r;
}
int cur_l,cur_r;
void add(int pos)
{
cnt[a[pos]]++;
// Condition for change in answer
ans += (sq(cnt[a[pos]])-sq(cnt[a[pos]]-1))*(a[pos]);
}
void del(int pos)
{
cnt[a[pos]]--;
// Condition for change in answer
ans += (sq(cnt[a[pos]])-sq(cnt[a[pos]]+1))*(a[pos]);
}
int32_t main()
{
SYNC
cin >> n;
int Q; cin >> Q;
block = sqrt(n);
for(int i = 0; i < n; i++) cin >> a[i];
vector<pt> v;
v.resize(Q);
for(int i = 0; i < Q; i++) {
cin >> v[i].l >> v[i].r;
v[i].l--, v[i].r--;
v[i].id = i;
}
sort(all(v),comp);
ans = cur_l = cur_r = 0;
vi res(Q);
for(int i = 0; i < Q; i++)
{
int L = v[i].l , R = v[i].r;
while(cur_l < L) {
del(cur_l);
cur_l++;
}
while(cur_l > L) {
add(cur_l-1);
cur_l--;
}
while(cur_r <= R) {
add(cur_r);
cur_r++;
}
while(cur_r > R+1) {
del(cur_r-1);
cur_r--;
}
res[v[i].id] = ans;
}
for(auto it : res) cout << it << '\n';
return 0;
}