Segment Tree hdu1166

Source: Internet
Author: User

Left son of line segment tree node [A, (A+B)/2] right son [(a+b)/2,b]

This is important.

The line tree as a complete binary tree calculation, open to 3*n, but it is best to 4*n

#include <bits/stdc++.h>using namespace std;int a[50005];struct {int sum; int left,right;}    b[50005*4];void Build (int left,int right,int i) {int mid;    B[i].left=left;b[i].right=right;        if (left==right) {b[i].sum=a[left];    return;    } mid = (left+right)/2;    Build (Left,mid,2*i);    Build (mid+1,right,2*i+1); B[i].sum=b[2*i].sum+b[2*i+1].sum;}    int Query (int left,int right,int i) {int mid;    if (b[i].left==left&&b[i].right==right) return b[i].sum;    Mid= (B[i].left + b[i].right)/2;    if (right <= mid) return Query (left,right,2*i);    else if (Left > Mid) return Query (left,right,2*i+1); else return query (left,mid,2*i) + query (mid+1,right,2*i+1);}    void Add (int id,int num,int i) {if (B[i].left = = b[i].right) {b[i].sum = b[i].sum + num; return;        } else {b[i].sum = b[i].sum + num;        if (id<=b[i*2].right) Add (id,num,2*i);    else Add (id,num,2*i+1);    }}int Main () {int t,kase=1;  scanf ("%d", &t);  while (t--) {memset (b,0,sizeof (b));        int n;        scanf ("%d", &n);        for (int i=1;i<=n;i++) scanf ("%d", &a[i]);        Build (1,n,1);        String S;int x, y;        printf ("Case%d:\n", kase++);            while (Cin>>s) {if (s[0]== ' E ') is break;            scanf ("%d%d", &x,&y);            if (s[0]== ' Q ') {printf ("%d\n", Query (x,y,1));            } if (s[0]== ' A ') {Add (x,y,1);        } if (s[0]== ' s ') Add (x,-y,1); }    }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Segment Tree hdu1166

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.