given an array, for each element, find out the total number of elements lesser than it, which appear to the right of it

后端 未结 10 1810
傲寒
傲寒 2021-02-04 11:43

I had previously posted a question, Given an array, find out the next smaller element for each element now, i was trying to know , if there is any way to find out \"given an ar

10条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 12:16

    You can also use binary Index tree

    int tree[1000005];
    void update(int idx,int val)
    {
       while(idx<=1000000)
       {
           tree[idx]+=val;
           idx+=(idx & -idx);
       }
    }
    
    int sum(int idx)
    {
        int sm=0;
        while(idx>0)
        {
           sm+=tree[idx];
           idx-=(idx & -idx);
        }
        return sm;
    }
    
    int main()
    {
        int a[]={4,2,1,5,3};
        int s=0,sz=6;
        int b[10];
        b[sz-1]=0;
        for(int i=sz-2;i>=0;i--)
        {
            if(a[i]!=0)
            {
                update(a[i],1);
                b[i]=sum(a[i]-1)+s;
            }
            else s++;
        }
        for(int i=0;i

提交回复
热议问题