Algorithm template--segment tree

Source: Internet
Author: User

Objective

Line tree as a high-level data structure, can do very very many things, then the line tree exactly what is it, we understand this

I. Basic CONCEPTS

The line tree is not a particularly advanced thing, as the name implies, it is also a tree. So why is it called a line tree? Because the nodes of the tree are some intervals, that is, line segments. So what does it look like?

Well, for example, it is a segment tree of the interval [1,9]. Some nodes are leaf nodes with a leaf node length of 1 and cannot continue to be divided. Leaf node record information is the most basic information, and other non-leaf nodes recorded is two sons of the merger of information (there are many methods of merger, specific analysis of the situation). The left and right intervals of the segment tree are \ ([L,mid], (mid,r]\). Moreover, since the segment tree is a binary tree, and the segment tree is a binary structure, it is very balanced and the depth is also \ (log_n\) level.

How to record? Record words, you can learn the construction method of the heap, the current point is \ (p\), the left son is \ (p*2\), the right son is \ (p*2+1\)

Two. Operation

Line tree is invented, there must be a reason, segment tree because it can quickly support some operations, it is widely used

1. Single Point modification

Advanced data structure must be able to modify the value, modify the words, only need to start from the root of the line tree, all the way to the leaf node, update the leaf node, and then the leaf node to the root of the path of the point on the road to update. The maximum time complexity is the depth of the segment tree, i.e. \ (O (log_n) \)

void change(){//丑陋的伪代码,x是我要修改的点的位置    if (到达叶子节点)        修改当前节点;        return;    }    int mid=区间中点;    if (x<=mid) 对左儿子进行操作;    if (x>mid)  对右儿子进行操作;    更新;}
2. Interval query

Before we get to the interval query, we need to know the interval decomposition

is the decomposition of the interval [2,8], and the red node represents the terminating node. All we have to do is merge all the terminating nodes together, which is the interval I want to break down. Also, there must be no more than 2 terminating nodes per layer. So, the interval query only need to find all the termination node, otherwise the complexity will rise to \ (O (n log_n) \), than violence is worse. Terminate node 2 per layer, so the complexity of the search is also \ (log_n\) magnitude

So how do I make sure I only find these termination zones?

int query(){//依然是丑陋的伪代码//l,r是线段树的区间,x,y是查询区间    if (x<=l&&r<=y) 返回节点信息;//线段树的区间完全包含在查询区间内    int mid=区间中点,ans;//如果不是完全包含则只需要做两个判断    if (x<=mid) ans=ans+左儿子信息;//查询的区间有部分在左儿子内    if (y>mid)  ans=ans+右儿子信息;//查询的区间有部分在右儿子内    return ans;}

(Pseudocode is really ugly ...) There's a real code below)

Three. Example 1.

Description

Given a series, there are two kinds of operations, one is to modify an element, and the other is to find the continuity of the interval.

Input

The first row of the input data contains two positive integers n,m (n<=100000,m<=500000), and the following are m rows,
Each line has three positive integers k,a,b (k=0 or 1, a,b<=n).
K=0 indicates the number of all numbers in the query interval [a, b] when the number a is added to B,k=1.

Output

For each query output, the corresponding answer.

Violent words,\ (O (n^2) \) complexity, if \ ( n\) to \ (10^6\) , this is obviously not possible. This time, we need to use the line tree to complete the problem. Single-point modification, interval query, line tree is very easy to achieve

#include <cmath>#include <cstdio>#include <cstring>#include <iostream>using namespaceStdConst intn=1e5;intval[n*4+10];intRead () {intx=0, f=1;CharCh=getchar (); for(;ch<' 0 '|| Ch>' 9 '; Ch=getchar ())if(ch=='-') f=-1; for(; ch>=' 0 '&&ch<=' 9 '; Ch=getchar ()) x=x*Ten+ch-' 0 ';returnX*f;}voidChangeintPintLintRintXintT) {if(L==R) {val[p]+=t;return; }intMid= (l+r) >>1;if(x<=mid) Change (p*2, l,mid,x,t);ElseChange (p*2+1, mid+1, r,x,t);//Modify the left and right son, because of the reasons for the achievements, so in the x<=mid of the time to modify the sonval[p]=val[p*2]+val[p*2+1];}intGetintPintLintRintXintY) {//Control pseudo-code can    if(x<=l&&r<=y)returnVAL[P];intMid= (l+r) >>1;intans=0;if(X<=mid) Ans+=get (p*2, l,mid,x,y);if(Y>mid) Ans+=get (p*2+1, mid+1, r,x,y);returnAns;}intMain () {intN=read (), M=read (); for(intI=1; i<=m;i++) {intK=read (), X=read (), Y=read ();if(!k) Change (1,1, n,x,y);if(k) printf ("%d\n", Get (1,1, n,x,y)); }return 0;}

For simple single-point modification and interval queries, we only need to consider what information is maintained on the node, how to modify it, and ask for these values.

2.

Description
Given a row n positive integers a[1]. A[n].
M inquiry, each query given an interval [l,r], output A[L]. A[R] The maximum common factor.

Input
The first row of two integers n,m.
The second row n integers represent a[1]. A[n].
The following m lines, 2 integers per line, indicate the left and right endpoints of the asking interval.

Output
A total of M lines, each representing an answer to an inquiry.

This problem does not involve the modification operation, only the query operation. But the query is lookup \ (gcd\). Therefore, for the leaf node maintenance point value, non-leaf node on the maintenance of two sons node \ (gcd\) can

#include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include < Algorithm> #define INF 0x7f7f7f7fusing namespace std;typedef long long ll;typedef unsigned int ui;typedef unsigned long    Long Ull;inline int read () {int X=0,f=1;char ch=getchar (); for (;ch< ' 0 ' | |    Ch> ' 9 '; Ch=getchar ()) if (ch== '-') f=-1;    for (; ch>= ' 0 ' &&ch<= ' 9 '; Ch=getchar ()) x= (x<<1) + (x<<3) +ch-' 0 '; return x*f;}    inline void print (int x) {if (x>=10) print (X/10); Putchar (x%10+ ' 0 ');} const int N=1e3,limit=1e9;int tree[n*4+10]; #define LS (p<<1) #define RS (p<<1|1) int gcd (int a,int b) {return!b ? A:GCD (b,a%b);} void Updata (int p) {TREE[P]=GCD (Tree[ls],tree[rs]);}        void build (int p,int l,int R) {if (l==r) {tree[p]=read ();    Return    } int mid= (L+R) >>1;    Build (Ls,l,mid), build (RS,MID+1,R); Updata (P);}    int query (int p,int l,int r,int x,int y) {if (x<=l&&r<=y) return tree[p]; int mid= (L+R) >>1,ans=0;    if (x<=mid) ans=gcd (Ans,query (ls,l,mid,x,y));    if (y>mid) ans=gcd (Ans,query (rs,mid+1,r,x,y)); return ans;}    int main () {int n=read (), M=read ();    Build (1,1,n);    for (int i=1,x,y;i<=m;i++) X=read (), Y=read (), printf ("%d\n", Query (1,1,n,x,y)); return 0;}
Four. Epilogue

We've talked so much, just talking about the single-point modification and interval query of the segment tree. So how does the interval change work? See the line tree for the lazy sign

Algorithm template--segment tree

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.