-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSparseTable.cpp
More file actions
76 lines (76 loc) · 1.74 KB
/
Copy pathSparseTable.cpp
File metadata and controls
76 lines (76 loc) · 1.74 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
66
67
68
69
70
71
72
73
74
75
76
#include <bits/stdc++.h>
#define N 1000000007
#define M 1000000000
using namespace std;
typedef long long int lli;
typedef pair<int,int> pii;
typedef tuple<int,int,int> tii;
//Sparse Table
int rangeMinQueries(int *a,int **sparse,int n,int low,int high)
{
int l=high-low+1;
int k=floor(log2(l));
int val1,val2;
val1=val2=INT_MAX;
val1=sparse[low][k];
int left=l-(int)pow(2,k);
if(left==0)
return a[val1];
val2=sparse[low+left][k];
return min(a[val1],a[val2]);
}
void createTree(int *a,int **sparse,int n)
{
int temp=floor(log2(n))+1;
for(int i=0;i<n;i++)
sparse[i][0]=i;
for(int i=1;i<temp;i++)
{
int j=0;
int temp=(int)pow(2,i-1);
while(j+temp<n)
{
int val;
if(a[sparse[j][i-1]]<a[sparse[j+temp][i-1]])
{
val=sparse[j][i-1];
}
else
{
val=sparse[j+temp][i-1];
}
sparse[j][i]=val;
j++;
}
}
}
int main()
{
int n;
cout<<"Enter no. of elements"<<endl;
cin>>n;
int *a=new int[n];
cout<<"Enter elements"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int col=floor(log2(n))+1;
int **sparse=(int **)calloc(n,sizeof(int *));
for(int i=0;i<n;i++)
sparse[i]=(int *)calloc(col,sizeof(int));
createTree(a,sparse,n);
cout<<"Spare table"<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<col;j++)
{
cout<<sparse[i][j]<<" ";
}
cout<<endl;
}
cout<<"Queries"<<endl;
cout<<rangeMinQueries(a,sparse,n,3,5)<<endl;
cout<<rangeMinQueries(a,sparse,n,0,5)<<endl;
cout<<rangeMinQueries(a,sparse,n,0,3)<<endl;
return 0;
}
//4 6 1 5 7 3