离散化:离散态二分转聚集态
离散化:用数字相对值替代绝对值
离散化 = 排序 + 离散化(分配位置) + 归位(离散化后的值放回原地址)
对于n个数m次查询,离散大小= n + m,即n次插入,m次查询的和的大小
- 去重 + 删除
sort(alls.begin(), alls.end());
.erase(unique(alls.begin(), alls.end()), alls.end());//去重 + 删除重复数字
手工编码
对于插入和查询都放在一个离散数组中,然后排序去重后,二分(lower_bound)去找离散状态下的对应值,然后进行操作
lower_bound:(起点,终点,查找的值) - 起点(变为值) + 1(vector映射到从0开始)
lower_bound(alls.begin(), alls.end(), x) - alls.begin() + 1;
unique自定义函数:返回结尾迭代器 - 开头 = 实际元素和
unique(.begin(), .end(), cmp) - .begin();
点击查看代码
const int N = 3e5 + 10;
typedef pair<int, int> PII;
int a[N], s[N];
vector<int> alls;
vector<PII> add, query;
int n, m;
int main() {
cin >> n >> m;
for(int i = 0; i < n; ++ i) {
int x, c;
cin >> x >> c;
alls.emplace_back(x);
add.emplace_back(x, c);
}
for(int i = 0; i < m; ++ i) {
int l, r;
cin >> l >> r;
alls.emplace_back(l), alls.emplace_back(r);
query.emplace_back(l, r);
}
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
for(auto i : add) {
int x = lower_bound(alls.begin(), alls.end(), i.first) - alls.begin() + 1;
a[x] += i.second;
}
for(int i = 1; i <= alls.size(); ++ i) {
s[i] = s[i - 1] + a[i];
}
for(auto i : query) {
int l = lower_bound(alls.begin(), alls.end(), i.first) - alls.begin() + 1,
r = lower_bound(alls.begin(), alls.end(), i.second) - alls.begin() + 1;
cout << s[r] - s[l - 1] << endl;
}
map与unorder_map的对比:

浙公网安备 33010602011771号