diff options
| author | Paul Jungeblut <paul.jungeblut@gmail.com> | 2017-12-22 12:49:35 +0100 |
|---|---|---|
| committer | Paul Jungeblut <paul.jungeblut@gmail.com> | 2017-12-22 12:49:35 +0100 |
| commit | 9facd3655e2b86799699a6fdbd566cb4b2a7fb1c (patch) | |
| tree | 4508df092aa1810d44f35be7f77e5ec3b38f7ca1 /datastructures/sparseTable.cpp | |
| parent | 488c92db019d01284cceeb2b8a1ac26c74001aeb (diff) | |
Adding new code for sparse table implementation and LCA.
Diffstat (limited to 'datastructures/sparseTable.cpp')
| -rw-r--r-- | datastructures/sparseTable.cpp | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/datastructures/sparseTable.cpp b/datastructures/sparseTable.cpp new file mode 100644 index 0000000..52867de --- /dev/null +++ b/datastructures/sparseTable.cpp @@ -0,0 +1,27 @@ +struct SparseTable { + int st[MAX_N][MAX_LOG + 1], log[MAX_N + 1]; // Achtung: 2^MAX_LOG > MAX_N + vector<int> *a; + + // Funktion muss idempotent sein! Hier Minimum. + bool better(int lidx, int ridx) { return a->at(lidx) <= a->at(ridx); } + + void init(vector<int> *vec) { + a = vec; + for (int i = 0; i < (int)a->size(); i++) st[i][0] = i; + for (int j = 1; j <= MAX_LOG; j++) { + for (int i = 0; i + (1 << j) <= (int)a->size(); i++) { + st[i][j] = better(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]) + ? st[i][j - 1] : st[i + (1 << (j - 1))][j - 1]; + }} + + log[1] = 0; + for (int i = 2; i <= MAX_N; i++) log[i] = log[i/2] + 1; + } + + // Gibt Index des Ergebnisses in [l,r]. Laufzeit: O(1) + int queryIdempotent(int l, int r) { + int j = log[r - l + 1]; + return better(st[l][j], st[r - (1 << j) + 1][j]) + ? st[l][j] : st[r - (1 << j) + 1][j]; + } +}; |
