-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsparse.cpp
More file actions
65 lines (56 loc) · 1.08 KB
/
sparse.cpp
File metadata and controls
65 lines (56 loc) · 1.08 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
namespace sparse{
int * M;
int M_offset;
int get(int i, int j){
return M[i*M_offset+j];
}
void set(int i, int j, int element){
M[i*M_offset+j]=element;
}
void print(){
for(int i=1;i<=SPARSE_SIZE;i++){
for(int j=0;j<=log2(SPARSE_SIZE)+1;j++){
std::cout << get(i,j) <<", ";
}
std::cout << "\n";
}
}
int RMQ(int * A, int i, int j){
if(i==j) return i;
int l = log2(j-i+1);
int r1 = A[get(i,l)];
int temp = j-power2(l)+1;
int r2 = A[get(temp,l)];
if(r1 <= r2){
return get(i,l);
}
else{
return get(j-power2(l)+1,l);
}
}
void construct(){
M_offset = log2(SPARSE_SIZE)+1;
M = (int *) malloc((SPARSE_SIZE+1)*(log2(SPARSE_SIZE)+1)*sizeof(int));
}
void preprocess(int * A){
for(int j=0;j<=log2(SPARSE_SIZE);j++){
for(int i=1;i<=SPARSE_SIZE;i++){
if(j==0) set(i,j,i);
else if(i+power2(j)-1>SPARSE_SIZE) continue;
else{
int temp1 = get(i,j-1);
int temp2 = get(i+power2(j-1),j-1);
if(A[temp1]<=A[temp2]){
set(i,j,temp1);
}
else{
set(i,j,temp2);
}
}
}
}
}
void del(){
free(M);
}
}