0

Given an array a[] has n non-negative elements. We have 2 types of queries:

A x y v: Find the first index i (x<=i<=y) that a[i]>v

B u v: Update a[u]=v;

I use segment tree but it's TLE in some test.

This is my code.

it max(it A,it B)
{
    it C;
    C.mx=max(A.mx,B.mx);
    return C;
}

This is the function that build the first tree.

void build(int id,int l,int r)
{
    if(l==r)
    {
        st[id].mx=a[l];
        st[id].pos=l;
        return;
    }
    int m=l+r>>1;
    build(id<<1,l,m);
    build(id<<1|1,m+1,r);
    st[id]=max(st[id<<1],st[id<<1|1]);
}

The update query:

void update(int id,int l,int r,int u,int v)
{
    if(u<l||r<u) return;
    if(l==r)
    {
        st[id].mx=v;
        return;
    }
    int m=l+r>>1;
    update(id<<1,l,m,u,v);
    update(id<<1|1,m+1,r,u,v);
    st[id]=max(st[id<<1],st[id<<1|1]);
}

The "find" query:

int getmin(int id,int l,int r,int u,int v,int value)
{
    if(v<l||r<u) return 1e9;
    if(l==r)
    {
        return st[id].pos;
    }
    int m=l+r>>1;
    //cout<<"->"<<id<<" "<<l<<" "<<r<<endl;
    if(st[id<<1].mx<=value)
    {
        if(st[id<<1|1].mx<=value)
            return 1e9;
        else return getmin(id<<1|1,m+1,r,u,v,value);
    }
    else
    {
        if(st[id<<1|1].mx<=value)
            return getmin(id<<1,l,m,u,v,value);
        else return min(getmin(id<<1,l,m,u,v,value),getmin(id<<1|1,m+1,r,u,v,value));
    }
}
aka61bt
  • 57
  • 4

1 Answers1

0

The query of your problem is "Find the first index i", but your code getmin find the minimun val > v in [x,y].

That's what you expected? The sentence return min(getmin(id<<1,l,m,u,v,value),getmin(id<<1|1,m+1,r,u,v,value)) is the reason causes TLE.

If you want to find the first index i (x<=i<=y) that a[i]>v, uses the code (uncheck) below to get the max value in an interval, than use binary search to find the first index.

int getMax(int id,int l,int r,int x,int y)
{
    if(x <= l && r <= y) return st[id].mx;
    if(l > y || r < x) return -1e9;
    
    int m=l+r>>1;
    return max(getMax(id<<1,l,m,x,y), getMax(id<<1|1,m+1,r,x,y));
}

/* 
 * ROOT is the root of the segtree.
 * L,R are the index bound of segtree.
 * return -1 if no such element.
 * */
int getFirstIndex(int x, int y, int v) {
   
   if(getMax(ROOT, L, R, x, y) <= v) return -1;
   
   int mid = -1;
   while(x <= y) {
       mid = (x + y) >> 1;
       if(getMax(ROOT,L,R,x, mid) > v) {
          y = mid - 1;
       } else{
          x = mid + 1;
       }
   }
   return x;
}

Ander
  • 66
  • 6