-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSparseTable.cpp
More file actions
32 lines (28 loc) · 814 Bytes
/
SparseTable.cpp
File metadata and controls
32 lines (28 loc) · 814 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class SparseTable {
vector<vector<int>> dp;
public:
SparseTable(const vector<int>& fun) :
dp(log2(fun.size()) + 1, vector<int>(fun.size())) {
dp[0] = fun;
for (int i = 1; i < int(dp.size()); i++)
for (int j = 0; j < int(fun.size()); j++)
dp[i][j] = dp[i - 1][dp[i - 1][j]];
}
int nthIteration(int x, int n) {
for (int bit = 0; bit <= int(dp.size()); bit++)
if (n & (1 << bit))
x = dp[bit][x];
return x;
}
int partition(int l, int r) {
int ans = 1;
for (int i = dp.size() - 1; i >= 0; i--)
if (dp[i][l] <= r) {
l = dp[i][l];
ans += (1 << i);
}
return ans;
}
};