Data Structure-segment tree (c + +)

Source: Internet
Author: User

Source:

#include <cstdio>
int m,n,num (0), h[100001];
struct Treetype
{
int left,right,lefts,rights,sum;//In this code, the semi-open half-closed interval is applied.
}i[200020]; The number of nodes of a complete binary tree is applied.
void x1 (int t1,int T2)//achievements.
{
int t=++num;//Note that in the line segment tree, always follow the left small right large principle.
i[t].left=t1;
i[t].right=t2;
if (t1!=t2-1)
{
i[t].lefts=num+1;//using the left small right large principle, numbering.
X1 (T1, (T1+T2)/2);
i[t].rights=num+1;
X1 ((T1+T2)/2,t2);//Note that this is a half-open half-closed interval.
i[t].sum=i[i[t].lefts].sum+i[i[t].rights].sum;//use backtracking to make intervals and updates.
}
Else
I[T].SUM=H[T1];
}
void x2 (int t,int x,int y)//modified.
{
if (i[t].left==i[t].right-1)//Note, this is a half-open half-closed interval.
i[t].sum+=y;
Else
{
if (x< (i[t].left+i[t].right)/2)//Use dichotomy to modify the node.
x2 (i[t].lefts,x,y);
if (x>= (i[t].left+i[t].right)/2)//Note that this is a half-open half-closed interval.
x2 (i[t].rights,x,y);
i[t].sum=i[i[t].lefts].sum+i[i[t].rights].sum;//use backtracking to make intervals and updates.
}
}
int x3 (int t,int x,int y)//sum.
{
if (x<=i[t].left&&y>=i[t].right)//At this time, the desired interval contains this interval.
return i[t].sum;
int ans (0);
if (x< (i[t].left+i[t].right)/2)//separates the desired interval.
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);//Note that this is a half-open half-closed interval.
scanf ("%d", &m);
for (int a=1;a<=m;a++)
{
int x, y, Z;
scanf ("%d%d%d", &x,&y,&z);
if (x==1)
x2 (1,y,z);
Else
printf ("%d\n", X3 (1,y,z+1));//Note that this is a half-open half-closed interval.
}
return 0;
}

Data Structure-segment tree (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.