题面

大秦为你打开题目传送门

题目描述

一个集合 $S$ ,初始为空。现有三个操作:

  1. $add$ :向集合里加入数 $x$ ,保证加入前集合中没有数 $x$ ;

  2. $del$ :从集合中删除数 $x$ ,保证删除前集合中有 $x$ ;

  3. $sum$ :设当前集合中有 $k$ 个数字,将集合中的数字进行升序排序,结果为 $a_1 <a_2 <a_3 <… <a_k$ 询问将集合里的数从小到大排序后,求 $\sum\limits_{ i \mod 5 = 3}^{i≤k} a_i$ 。

现有 $n$ 次操作,对于每个 $sum$ 操作,输出答案。

思路

这道题目很简单,对于每次插入,维护这段区间模五以后的和(当然是权值线段树)

代码

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#pragma GCC optimize(3, "Ofast", "inline")
#include<bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;
typedef long long ll;

int n;
pair<string , int >op[N];

vector<int >U;
int Usz;

struct Node {
int L, R;
vector<ll >sum;
int len;

Node() { sum.resize(5); }
Node(int L, int R, int len) : L(L), R(R), len(len) {
sum.resize(5);
for(int i = 0; i < 5; i++) sum[i] = 0;
}
inline ll& operator [] (int x) { return sum[x]; }

inline Node operator + (Node & b) const {
Node ans(min(L, b.L), max(R, b.R), len + b.len);
for(int i = 0; i < 5; i++) {
ans[i] = sum[i] + b[(i - len % 5 + 5) % 5];
}
return ans;
}
};
class SegTree {
private :
Node node[N << 2];
public :
void Build(int p, int L, int R) {
node[p] = Node(L, R, 0);
if(L == R) return ;
int mid = L + R >> 1;
Build(p << 1, L, mid), Build(p << 1 | 1, mid + 1, R);
}
void Modify(int p, int x, int v) {
if(node[p].L == node[p].R) {
node[p][0] += v * U[x - 1];
node[p].len += v;
return ;
}
int mid = node[p].L + node[p].R >> 1;
if(x <= mid) Modify(p << 1, x, v);
else Modify(p << 1 | 1, x, v);
node[p] = node[p << 1] + node[p << 1 | 1];
}
ll Query(int p) {
return node[1][p - 1];
}
};

SegTree tree;

void Input() {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> op[i].first;
op[i].second = -1;
if(op[i].first != "sum") {
cin >> op[i].second;
U.push_back(op[i].second);
}
}
}

void Work() {
sort(U.begin(), U.end());
U.erase(unique(U.begin(), U.end()), U.end());
Usz = U.size();
tree.Build(1, 1, Usz);
for(int i = 1; i <= n; i++) {
int pos = -1;
if(op[i].second != -1) {
pos = lower_bound(U.begin(), U.end(), op[i].second) - U.begin() + 1;
}
if(op[i].first == "add") {
tree.Modify(1, pos, 1);
}
else if(op[i].first == "del") {
tree.Modify(1, pos, -1);
}
else {
printf("%lld\n", tree.Query(3));
}
}
}

int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
Input();
Work();
return 0;
}