A very minimalized segment tree that I happened to write while being boring.
Supports interval queries on maximum values and single-node modifications. This code is proven correct.
class SegmentTreeMini
{
public:
int n, lb[maxn], rb[maxn], mx[maxn];
void init(int n_) { n=1; while(n<n_)n*=2;
for (int i=1;i<=n;i++) {int id=n-1+i;
lb[id]=rb[id]=i;mx[id]=0;}
for (int i=n-1;i>=1;i--) {lb[i]=lb[2*i];
rb[i]=rb[2*i+1];mx[i]=0;}
return ; }
int query(int p, int l, int r) {
if (lb[p]==l&&rb[p]==r) { return mx[p]; }
if (rb[2*p]>=r) return query(2*p,l,r);
else if (lb[2*p+1]<=l) return query(2*p+1,l,r);
else return max(query(2*p,l,rb[2*p]),query(2*p+1,lb[2*p+1],r));
} int query(int l, int r) { if(l>r) return 0; return query(1,l,r); }
void change(int p, int l, int v) {
if (lb[p]==l&&rb[p]==l) { mx[p]=max(mx[p],v); return ; }
if (rb[2*p]>=l) change(2*p,l,v);
else if (lb[2*p+1]<=l) change(2*p+1,l,v);
else change(2*p,l,v),change(2*p+1,l,v);
mx[p]=max(mx[2*p],mx[2*p+1]);
} void change(int l, int v) { change(1,l,v); }
} st;
Somehow it is worthwhile debugging the symbols and operators where you could make typos typing <=
operators to >=
operators which throw the following rubbish:
Reading symbols from formation.cpp.exe...done.
(gdb) r
Starting program: D:\Desktop\formation.cpp.exe
[New Thread 1628.0x118c]
[New Thread 1628.0x13d0]
5 1 2 4 3 5 5 2 3 4 1
Program received signal SIGSEGV, Segmentation fault.
0x0000000000425f82 in SegmentTreeMini::query (this=0x4ac040 <st>, p=262144, l=1, r=5)
at D:\Desktop\formation.cpp:24
24 if (rb[2*p]<=r) return query(2*p,l,r);
(gdb) p lb
$1 = {0, 1, 1, 5, 1, 3, 5, 7, 1, 2, 3, 4, 5, 6, 7, 8, 0 <repeats 49994 times>}
(gdb) p rb
$2 = {0, 8, 4, 8, 2, 4, 6, 8, 1, 2, 3, 4, 5, 6, 7, 8, 0 <repeats 49994 times>}
(gdb)