Segment Trees Extremely versatile. Basic Segment Tree void add(int pos, int val); int range_sum(int start, int end); Three ways below of visualizing it.

Slides:



Advertisements
Similar presentations
Fenwick Tree (binary indexed tree).
Advertisements

INTERVAL TREE & SEGMENTATION TREE
Cutting trees and the cutting lemma Presented by Amir Mograbi.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part R4. Disjoint Sets.
BackTracking Algorithms
Efficient access to TIN Regular square grid TIN Efficient access to TIN Let q := (x, y) be a point. We want to estimate an elevation at a point q: 1. should.
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Chapter 4: Trees Part II - AVL Tree
I/O-Algorithms Lars Arge Fall 2014 September 25, 2014.
Types of Algorithms.
1 Disjoint Sets Set = a collection of (distinguishable) elements Two sets are disjoint if they have no common elements Disjoint-set data structure: –maintains.
1 CSE 373 AVL trees, continued read: Weiss Ch. 4, section slides created by Marty Stepp
Segment Trees. Longest Non Decreasing Subsequence (Revisited) Length of LNDS ending at i th Loc This runs in O(n 2 ). Can we do.
They’re not just binary anymore!
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
Trees II Kruse and Ryba Ch 10.1,10.2,10.4 and 11.3.
Main Index Contents 11 Main Index Contents Tree StructuresTree Structures (3 slides) Tree Structures Tree Node Level and Path Len. Tree Node Level and.
CS 261 – Data Structures Priority Queues & Heaps.
Binary Search Introduction to Trees. Binary searching & introduction to trees 2 CMPS 12B, UC Santa Cruz Last time: recursion In the last lecture, we learned.
CS 206 Introduction to Computer Science II 02 / 11 / 2009 Instructor: Michael Eckmann.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary Trees.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Introduction to trees.
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
TREES A tree's a tree. How many more do you need to look at? --Ronald Reagan.
Computer Science and Software Engineering University of Wisconsin - Platteville 12. Heap Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++ Plus.
Data Structure (III) GagGuy.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
TECH Computer Science Data Abstraction and Basic Data Structures Improving efficiency by building better  Data Structure Object IN  Abstract Data Type.
Trees By Charl du Plessis. Contents Basic Terminology Basic Terminology Binary Search Trees Binary Search Trees Interval Trees Interval Trees Binary Indexed.
CSC 107 – Programming For Science. Today’s Goal Variables  Variable  Variable name location to store data  Only for humans; 0 x 7E8A2410 harder to.
Houyang 3/25/13. USACO March Contest Congrats to Johnny Ho for scoring over 900 points in the Gold Division o 7th place in US Kudos to Jonathan Uesato.
Binary Search From solving a problem to verifying an answer.
DP (not Daniel Park's dance party). Dynamic programming Can speed up many problems. Basically, it's like magic. :D Overlapping subproblems o Number of.
CSC 107 – Programming For Science. Today’s Goal  Become familiar with simple arrays  Declaring an array variable  Assigning data to array entries 
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CSE373: Data Structures & Algorithms Lecture 11: Implementing Union-Find Nicki Dell Spring 2014.
CSE373: Data Structures & Algorithms Lecture 10: Implementing Union-Find Dan Grossman Fall 2013.
Foundations of Data Structures Practical Session #8 Heaps.
AVL Trees 1. 2 Outline Background Define balance Maintaining balance within a tree –AVL trees –Difference of heights –Rotations to maintain balance.
Week 13 - Friday.  What did we talk about last time?  Sorting  Insertion sort  Merge sort  Started quicksort.
Problem of the Day  Can you move exactly one glass to arrange the glasses containing orange juice to be next to one another?
CS 206 Introduction to Computer Science II 10 / 02 / 2009 Instructor: Michael Eckmann.
Heapsort. What is a “heap”? Definitions of heap: 1.A large area of memory from which the programmer can allocate blocks as needed, and deallocate them.
CSE 143 Lecture 21 Binary Search Trees, continued read slides created by Marty Stepp
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
AVL Trees and Heaps. AVL Trees So far balancing the tree was done globally Basically every node was involved in the balance operation Tree balancing can.
Interval S = [3,10]  {x | 3 ≤ x ≤ 10} Closed segment S = (3,10)  {x | 3 < x < 10} Opened segment S = [3,3]  {3} Point.
Mergeable Heaps David Kauchak cs302 Spring Admin Homework 7?
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
7 Finding Bridge in a Graph. What is a bridge ? A C D B F G E.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Problem of the Day  Can you move exactly one glass to arrange the glasses containing orange juice to be next to one another?
AVL Trees. AVL Tree In computer science, an AVL tree is the first-invented self-balancing binary search tree. In an AVL tree the heights of the two child.
Graphs. What is a graph? In simple words, A graph is a set of vertices and edges which connect them. A node (or vertex) is a discrete position in the.
UNC Chapel Hill M. C. Lin Geometric Data Structures Reading: Chapter 10 of the Textbook Driving Applications –Windowing Queries Related Application –Query.
Interval Trees Marco Gallotta. Problem ● Given a collection of items i, each with value V i ● Want to answer many queries of the form: How many items.
Lecture 19: Binary Trees reading: 17.1 – 17.3
B-Tree Michael Tsai 2017/06/06.
Data Structures: Disjoint Sets, Segment Trees, Fenwick Trees
Building Java Programs
Data Structures: Segment Trees, Fenwick Trees
Wednesday, April 18, 2018 Announcements… For Today…
Tree A tree is a data structure in which each node is comprised of some data as well as node pointers to child nodes
Red-Black Trees Bottom-Up Deletion.
Representing binary trees with lists
Building Java Programs
Sum this up for me Let’s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i
Augmenting Data Structures: Interval Trees
Presentation transcript:

Segment Trees Extremely versatile

Basic Segment Tree void add(int pos, int val); int range_sum(int start, int end); Three ways below of visualizing it. Commonly stored in an array to save memory. Node i: Parent = i/2, left child = i *2, right child= i*

Add/Modify Add a certain value to bottom node. Propagate up the tree. Original segment tree-> Add 5 to value 5. New value is 10. Add 5 to every node along the path from the bottom node to the root. Changed nodes are highlighted

Add/Modify Code Note that SIZE is the size of the segment tree (We usually assume it to be a power of 2. You can always pad it with 0s to make it a power of 2). Also, the tree is stored with the root at node 1, its children at node 2 and 3, and so on… void add(int pos, int val) { //pos is 0-indexed int node = SIZE+pos; while(node > 0) { segTree[node] += val; node /= 2; }

Range Sum Sums up the values in a range. Select O(lgn) nodes to cover the range. Original segment tree. Range sum(1,4) The 3 nodes selected cover the range. Sum of range is sum of highlighted nodes

Range Sum Code Call recursive helper function. int sum(int start, int end) { return sum(1, start, end, 0, SIZE-1); } int sum(int node, int start, int end, int left, int right) { // Case 1: Intervals disjoint if(end<left || right<start) return 0; //Case 2: Current interval inside query interval if(start<=left && right<=end) return segTree[node]; //Case 3: Overlap, recurse on children return sum(node*2, start, end, left, (left+right)/2) + sum(node*2+1, start, end, (left+right)/2+1, right); }

Other operations For example, find minimum in range. void add(int pos, int val); int range_min(int start, int end); Add/modify code similar. Basically, a node’s value needs to be computed in O(1) time from its children

Lazy Propagation What if you need to modify a range? You need to BE LAZY! Store lazy value for each node. For updates, find the O(lgn) nodes that cover a range, and set their lazy value. Propagate lazy value to children when recursing on child nodes.

Lazy Propagation Let lazy[node] = value to be added to this interval. True value of node = segTree[node] + lazy[node] at all times (need to be able to determine true value of node from segTree and lazy in O(1) time). Example below: Add 5 to range [0,5]. Highlighted nodes are in range and modified. Can modify lazy and segTree or only lazy

Potw Farmer John has a large field of grass. Each of the N plots has a certain amount of grass. Bessie and the other cows choose an interval in which they want to graze. If Bessie and the cows graze on an interval, the amounts of grass in all plots in that interval are reduced by a certain amount. The cows can’t graze on an interval if it would cause the amount of grass to turn negative, so Farmer John must stop them. How many groups of cows does Farmer John need to stop?

Potw Input format: o Line 1: N C (N is the number of plots of grass and C is the number of groups of cows) o Line 2…N+1: G_i: The amount of grass in the i-th plot o Line N+2…N+C+1: A B C (If the cows graze, they decrease the amount of grass of each plot in [A, B] by C) Output format: o Line 1: A, the amount of groups of cows FJ has to turn away Constraints: o 1<=N,C<=1,000: 10 points o 1<=N,C<=100,000: 25 points Sample input: o 4 3 o 7 o 3 o 2 o 4 o o o Sample output: o 1