fenwick tree

Coordinate compression

Given an array, builds a map that assigns 0 to the smallest value, 1 to the next larger value, and so on.

[−20,1000,−20,7,42,7]⟼{−20↦07↦142↦21000↦3[-20, 1000, -20, 7, 42, 7] \quad\longmapsto\quad \left\{ \begin{aligned} -20 &\mapsto 0 \\ 7 &\mapsto 1 \\ 42 &\mapsto 2 \\ 1000 &\mapsto 3 \end{aligned} \right.

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. O(Nlog⁡N){O(N \log N)}

NN is the length of A.


Sum ranges over sparse positions

Say a problem gives you the length NN of a zero array and QQ queries as follows:

  • 0 i x: Add xx to position ii.
  • 1 l r: Find the sum over [l,r)[l, r).

You could use a Fenwick tree, but if NN is too large (say N=1013N = 10^{13}), it wouldn’t fit in memory.

Instead, read all the queries first and compress the indices ii, ll, and rr. Then use the compressed indices for the structure’s queries.

Original015  ⋯  620  ⋯  237  ⋯⏟Query [15,42)  042  ⋯  91012Compressed006122⏟Query [0,3)0394\begin{array}{rl} \text{Original} & \underbrace{\overset{15}{\boxed{0}}\;\cdots\;\overset{20}{\boxed{6}}\;\cdots\;\overset{37}{\boxed{2}}\;\cdots}_{\text{Query }[15,42)} \;\overset{42}{\boxed{0}}\;\cdots\;\overset{10^{12}}{\boxed{9}} \\[2em] \text{Compressed} & \mathord{\underbrace{\overset{0}{\boxed{0}}\overset{1}{\boxed{6}}\overset{2}{\boxed{2}}}_{\mathclap{\text{Query }[0,3)}}} \overset{3}{\boxed{0}}\overset{4}{\boxed{9}} \end{array}
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';
}