Data structure--segment Tree II (c + +)

Source: Internet
Author: User

Source:

#include <cstdio>
int n,num (0), h[100001];
struct Treetype
{
int left,right,lefts,rights,sum,sign;
}i[200020];
void x1 (int t1,int T2)//achievements.
{
int t=++num;
i[t].left=t1;
i[t].right=t2;
if (t1!=t2-1)
{
i[t].lefts=num+1;
X1 (T1, (T1+T2)/2);
i[t].rights=num+1;
X1 ((T1+T2)/2,t2);
i[t].sum=i[i[t].lefts].sum+i[i[t].rights].sum;
}
Else
I[T].SUM=H[T1];
}
void lazy (int t)//Use Jingxiang's lazy algorithm to deepen one layer down.
{
i[i[t].lefts].sum+=i[t].sign* (i[i[t].lefts].right-i[i[t].lefts].left);
i[i[t].rights].sum+=i[t].sign* (i[i[t].rights].right-i[i[t].rights].left);
i[i[t].lefts].sign+=i[t].sign;
i[i[t].rights].sign+=i[t].sign;
i[t].sign=0;
}
void x2 (int t,int x,int y,int z)
{
if (x<=i[t].left&&y>=i[t].right)
{
i[t].sum+=z* (i[t].right-i[t].left);
i[t].sign+=z;//may also have a processed mark, so it should be superimposed.
}
Else
{
if (i[t].sign)//To continue searching down, prepare ahead.
lazy (t);
if (x< (i[t].left+i[t].right)/2)
x2 (i[t].lefts,x,y,z);
if (y> (i[t].left+i[t].right)/2)
x2 (i[t].rights,x,y,z);
i[t].sum=i[i[t].lefts].sum+i[i[t].rights].sum;
}
}
int x3 (int t,int x,int y)//sum.
{
if (x<=i[t].left&&y>=i[t].right)
return i[t].sum;
if (i[t].sign)//the same as above, to continue searching down, prepare ahead.
lazy (t);
int ans (0);
if (x< (i[t].left+i[t].right)/2)
ans+=x3 (i[t].lefts,x,y);
if (y> (i[t].left+i[t].right)/2)
ans+=x3 (i[t].rights,x,y);
return ans;
}
int main ()
{
scanf ("%d", &n);
for (int a=1;a<=n;a++)
scanf ("%d", &h[a]);
X1 (1,n+1);
scanf ("%d", &n);
for (int a=1;a<=n;a++)
{
int t;
scanf ("%d", &t);
if (t==1)
{
int x, y, Z;
scanf ("%d%d%d", &x,&y,&z);//Modify the interval range.
x2 (1,x,y+1,z);//semi-closed half-open interval processing.
}
Else
{
int x, y;
scanf ("%d%d", &x,&y);
printf ("%d\n", X3 (1,x,y+1));//The same as above, the semi-closed half-open interval in the form of processing.
}
}
return 0;
}

Data structure--segment Tree II (c + +)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.