hdu 3874 Necklace

本文从WordPress迁移而来, 查看全部WordPress迁移文章

线段树

跟三鲜图灵树一模一样的题目,不过数据小一些,省掉了离散化

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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define N 50010
#define M 200010
#define MAX 1000010
#define LL long long
#define cl(xx,yy) memset((xx),(yy),sizeof((xx)))
#define pb push_back

LL c[N];
int n,num[N],pre[MAX];
struct ASK{
int l,r;
LL res;
}ask[M];
vector<int>List[N];

inline int lowbit(int x){
return x & (-x);
}

void add(int pos,LL val){
while(pos <= n){
c[pos] += val; pos += lowbit(pos);
}
}

LL sum(int pos){
LL res = 0;
while(pos){
res += c[pos]; pos -= lowbit(pos);
}
return res;
}

int main(){
int q,cas;
scanf("%d",&cas);
while(cas--){
scanf("%d",&n);
for(int i = 1; i <= n; i++)
scanf("%d",&num[i]);
scanf("%d",&q);
for(int i = 1; i <= n; i++)
List[i].clear();
for(int i = 0; i < q; i++){
scanf("%d%d",&ask[i].l,&ask[i].r);
List[ask[i].r].pb(i);
}
cl(pre,-1); cl(c,0);
for(int i = 1; i <= n; i++){
if(pre[num[i]] != -1)
add(pre[num[i]],-num[i]);
add(i,num[i]);
pre[num[i]] = i;
if(!List[i].empty()){
for(int k = 0; k < List[i].size(); k++){
int id = List[i][k];
ask[id].res = sum(ask[id].r) - sum(ask[id].l - 1);
}
}
}
for(int i = 0; i < q; i++)
printf("%I64d\n",ask[i].res);
}
return 0;
}