【算法】线段树模板

struct node
{
    int left,right;
    int n;
} a[100];
int sum;
void build(int s,int t,int n)
{
    int mid=(s+t)/2;
    a[n].left=s;
    a[n].right=t;
    if (s==t) return;
    a[n].left=s;
    a[n].right=t;
    build(s,mid,2*n);
    build(mid+1,t,2*n+1);
}
void insert(int s,int t,int step)
{
    if (s==a[step].left && t==a[step].right)
    {
        a[step].n++;
        return;
    }
    if (a[step].left==a[step].right)   return;
    int mid=(a[step].left+a[step].right)/2;
    if (mid>=t) insert(s,t,step*2);
    else if (mid<s) insert(s,t,step*2+1);
    else
    {
        insert(s,mid,step*2);
        insert(mid+1,t,step*2+1);
    }
}
void count (int s,int t,int step)
{
    if (a[step].n!=0)
        sum=sum+a[step].n*(t-s+1);
    if (a[step].left==a[step].right)
        return;
    int mid=(a[step].left+a[step].right)/2;
    if (mid>=t)
        count(s,t,step*2);
    else if (mid<s)
        count(s,t,step*2+1);
    else
    {
        count(s,mid,step*2);
        count(mid+1,t,step*2+1);
    }
}

 

posted @ 2017-04-01 21:20  Nitrate  阅读(89)  评论(0)    收藏  举报