Coordinate compression
Given an array, builds a map that assigns 0 to the smallest value, 1 to the next larger value, and so on.
Implementation
map<int, int> compress(vector<int> A) {
sort(A.begin(), A.end());
map<int, int> M;
for (auto x : A) M.emplace(x, M.size());
return M;
}
Interface
| Operation | Description | Time |
|---|---|---|
compress(A) |
Returns the map from values in A to their compressed indices. |
is the length of A.
Sum ranges over sparse positions
Say a problem gives you the length of a zero array and queries as follows:
0 i x: Add to position .1 l r: Find the sum over .
You could use a Fenwick tree, but if is too large (say ), it wouldn’t fit in memory.
Instead, read all the queries first and compress the indices , , and . Then use the compressed indices for the structure’s queries.
Uses: Fenwick tree
int N, Q;
cin >> N >> Q;
vector<array<int, 3>> queries(Q);
vector<int> indices;
for (auto& [type, a, b] : queries) {
cin >> type >> a >> b;
indices.push_back(a);
if (type == 1) indices.push_back(b);
}
auto comp = compress(indices);
FenwickTree tree(comp.size());
for (auto [type, a, b] : queries) {
if (type == 0) tree.add(comp[a], b);
else cout << tree.sum(comp[a], comp[b]) << '\n';
}