SlideShare uma empresa Scribd logo
1 de 54
Baixar para ler offline
Segment Trees
           Problems




          Segment Trees

       League of Programmers
              ACA, IIT Kanpur




League of Programmers   Segment Trees
Segment Trees
                            Problems

Outline



  1   Segment Trees


  2   Problems




                 League of Programmers   Segment Trees
Segment Trees
                              Problems

A Simple Problem



  Problem Statement
  We have an array a[0 . . . n-1].




                   League of Programmers   Segment Trees
Segment Trees
                              Problems

A Simple Problem



  Problem Statement
  We have an array a[0 . . . n-1].




                   League of Programmers   Segment Trees
Segment Trees
                            Problems

A Simple Problem



  Problem Statement
  We have an array a[0 . . . n-1].
  We should be able to
    1 Find the sum of elements l to r




                 League of Programmers   Segment Trees
Segment Trees
                             Problems

A Simple Problem



  Problem Statement
  We have an array a[0 . . . n-1].
  We should be able to
    1 Find the sum of elements l to r

    2 Change in the value of a specied element of the array a[i]=x




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

A Simple Problem

  Possible Solutions




                  League of Programmers   Segment Trees
Segment Trees
                            Problems

A Simple Problem

  Possible Solutions
       Naive one: Go on from l to r and keep on adding and update
       the element when you get a update request.
       Running time: O(n) to sum and O(1) to update




                 League of Programmers   Segment Trees
Segment Trees
                              Problems

A Simple Problem

  Possible Solutions
       Naive one: Go on from l to r and keep on adding and update
       the element when you get a update request.
       Running time: O(n) to sum and O(1) to update
       Store sum from start to i at the i th index in an another array.
       Running time: O(1) to return sum, O(n) to update




                   League of Programmers   Segment Trees
Segment Trees
                              Problems

A Simple Problem

  Possible Solutions
       Naive one: Go on from l to r and keep on adding and update
       the element when you get a update request.
       Running time: O(n) to sum and O(1) to update
       Store sum from start to i at the i th index in an another array.
       Running time: O(1) to return sum, O(n) to update
       This works well if the number of query operations are large
       and very few updates




                   League of Programmers   Segment Trees
Segment Trees
                              Problems

A Simple Problem

  Possible Solutions
       Naive one: Go on from l to r and keep on adding and update
       the element when you get a update request.
       Running time: O(n) to sum and O(1) to update
       Store sum from start to i at the i th index in an another array.
       Running time: O(1) to return sum, O(n) to update
       This works well if the number of query operations are large
       and very few updates
       What if the number of query and updates are equal?




                   League of Programmers   Segment Trees
Segment Trees
                              Problems

A Simple Problem

  Possible Solutions
       Naive one: Go on from l to r and keep on adding and update
       the element when you get a update request.
       Running time: O(n) to sum and O(1) to update
       Store sum from start to i at the i th index in an another array.
       Running time: O(1) to return sum, O(n) to update
       This works well if the number of query operations are large
       and very few updates
       What if the number of query and updates are equal?
       Can we perform both the operations in O(log n) time once
       given the array?


                   League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree
         Leaf Nodes are the elements in the array.




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree
         Leaf Nodes are the elements in the array.

         Each internal node represents some merging of the leaf nodes




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree
         Leaf Nodes are the elements in the array.

         Each internal node represents some merging of the leaf nodes


     Number each node in the tree level by level




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree
         Leaf Nodes are the elements in the array.

         Each internal node represents some merging of the leaf nodes


     Number each node in the tree level by level
         Observe that for each node the left child is 2*i and right child

         is 2*i+1




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree
         Leaf Nodes are the elements in the array.

         Each internal node represents some merging of the leaf nodes


     Number each node in the tree level by level
         Observe that for each node the left child is 2*i and right child

         is 2*i+1

         For each node the parent is i/2




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree
         Leaf Nodes are the elements in the array.

         Each internal node represents some merging of the leaf nodes


     Number each node in the tree level by level
         Observe that for each node the left child is 2*i and right child

         is 2*i+1

         For each node the parent is i/2

         Just use an array to represent the tree, operate on indices to

         access parents and children




                League of Programmers   Segment Trees
Segment Trees
                           Problems

Segment Trees

     Representation of the tree
         Leaf Nodes are the elements in the array.

         Each internal node represents some merging of the leaf nodes


     Number each node in the tree level by level
         Observe that for each node the left child is 2*i and right child

         is 2*i+1

         For each node the parent is i/2

         Just use an array to represent the tree, operate on indices to

         access parents and children


     Note: An important feature of the tree segments is that they
     use linear memory: standard tree segments requires about 4n
     memory elements to work on an array of size n

                League of Programmers   Segment Trees
Segment Trees
                      Problems

Solution




           League of Programmers   Segment Trees
Segment Trees
                            Problems

Solution
      We start with a segment [0 . . . n-1]. and every time we divide
      the current period of two (if it has not yet become a segment
      of length), and then calling the same procedure on both
      halves, and for each such segment we store the sum on it.




                 League of Programmers   Segment Trees
Segment Trees
                             Problems

Solution
      We start with a segment [0 . . . n-1]. and every time we divide
      the current period of two (if it has not yet become a segment
      of length), and then calling the same procedure on both
      halves, and for each such segment we store the sum on it.
      In other words, we calculate and remember somewhere sum of
      the elements of the array, ie segment a[0 . . . n-1]. Also
      calculate the amount of the two halves of the array:
      a[0 . . . n/2] and a[n/2 + 1 . . . n − 1]. Each of the two halves, in
      turn, divide in half and count the amount to keep them, then
      divide in half again, and so on until it reaches the current
      segment length 1




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Solution
      We start with a segment [0 . . . n-1]. and every time we divide
      the current period of two (if it has not yet become a segment
      of length), and then calling the same procedure on both
      halves, and for each such segment we store the sum on it.
      In other words, we calculate and remember somewhere sum of
      the elements of the array, ie segment a[0 . . . n-1]. Also
      calculate the amount of the two halves of the array:
      a[0 . . . n/2] and a[n/2 + 1 . . . n − 1]. Each of the two halves, in
      turn, divide in half and count the amount to keep them, then
      divide in half again, and so on until it reaches the current
      segment length 1
      The number of vertices in the worst case is estimated at
                      n + n /2 + n /4 + n /8 + · · · + 1  2 n

                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Solution
      We start with a segment [0 . . . n-1]. and every time we divide
      the current period of two (if it has not yet become a segment
      of length), and then calling the same procedure on both
      halves, and for each such segment we store the sum on it.
      In other words, we calculate and remember somewhere sum of
      the elements of the array, ie segment a[0 . . . n-1]. Also
      calculate the amount of the two halves of the array:
      a[0 . . . n/2] and a[n/2 + 1 . . . n − 1]. Each of the two halves, in
      turn, divide in half and count the amount to keep them, then
      divide in half again, and so on until it reaches the current
      segment length 1
      The number of vertices in the worst case is estimated at
                      n + n /2 + n /4 + n /8 + · · · + 1  2 n
      The height of the tree is the value of the segments O(log n).
                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Building the tree




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Building the tree
       From the bottom up: rst write the values of the elements a[i]
       the corresponding leaves of the tree, then on the basis of these
       values to calculate the nodes of the previous level as the sum
       of the two leaves, then similarly calculate values for one more
       level, etc. Convenient to describe the operation recursively.




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Building the tree
       From the bottom up: rst write the values of the elements a[i]
       the corresponding leaves of the tree, then on the basis of these
       values to calculate the nodes of the previous level as the sum
       of the two leaves, then similarly calculate values for one more
       level, etc. Convenient to describe the operation recursively.
       Time to do this?




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Building the tree
       From the bottom up: rst write the values of the elements a[i]
       the corresponding leaves of the tree, then on the basis of these
       values to calculate the nodes of the previous level as the sum
       of the two leaves, then similarly calculate values for one more
       level, etc. Convenient to describe the operation recursively.
       Time to do this?




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Building the tree
       From the bottom up: rst write the values of the elements a[i]
       the corresponding leaves of the tree, then on the basis of these
       values to calculate the nodes of the previous level as the sum
       of the two leaves, then similarly calculate values for one more
       level, etc. Convenient to describe the operation recursively.
       Time to do this?
       O(n) since each node in the tree is modied once and uses
       only a max of 2 nodes (already computed) for computation.




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Query Request




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Query Request
      The input is two numbers l and r. And we have the time
      O (logn). Calculate the sum of the segment a[l . . . r ] .




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Query Request
      The input is two numbers l and r. And we have the time
      O (logn). Calculate the sum of the segment a[l . . . r ] .
      Can be done recursively




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Query Request
      The input is two numbers l and r. And we have the time
      O (logn). Calculate the sum of the segment a[l . . . r ] .
      Can be done recursively
           If your range is within the segment completely, return the

           value at that node




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Query Request
      The input is two numbers l and r. And we have the time
      O (logn). Calculate the sum of the segment a[l . . . r ] .
      Can be done recursively
           If your range is within the segment completely, return the

           value at that node

           If its completely out of range, return 0 or null




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Query Request
      The input is two numbers l and r. And we have the time
      O (logn). Calculate the sum of the segment a[l . . . r ] .
      Can be done recursively
           If your range is within the segment completely, return the

           value at that node

           If its completely out of range, return 0 or null

           If its in one of the child, query on that child




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Query Request
      The input is two numbers l and r. And we have the time
      O (logn). Calculate the sum of the segment a[l . . . r ] .
      Can be done recursively
           If your range is within the segment completely, return the

           value at that node

           If its completely out of range, return 0 or null

           If its in one of the child, query on that child

           If its in both the child, do query on both of them




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation
  Query Request
  Pseudocode
    query(node,l,r) {
     if range of node is within l and r
      return value in node
     else if range of node is completely outside l and r
      return 0
     else
      return
  sum(query(left-child,l,r),query(right-child,l,r))
  }




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation
  Query Request
  Pseudocode
    query(node,l,r) {
     if range of node is within l and r
      return value in node
     else if range of node is completely outside l and r
      return 0
     else
      return
  sum(query(left-child,l,r),query(right-child,l,r))
  }
      But this doesn't look O(log n)




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation
  Query Request
  Pseudocode
    query(node,l,r) {
     if range of node is within l and r
      return value in node
     else if range of node is completely outside l and r
      return 0
     else
      return
  sum(query(left-child,l,r),query(right-child,l,r))
  }
      But this doesn't look O(log n)


      It is.

      At any level of the tree, the maximum number of segments that

      could call our recursive function when processing a request is 4.




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation
  Query Request
  Pseudocode
    query(node,l,r) {
     if range of node is within l and r
      return value in node
     else if range of node is completely outside l and r
      return 0
     else
      return
  sum(query(left-child,l,r),query(right-child,l,r))
  }
      But this doesn't look O(log n)


      It is.

      At any level of the tree, the maximum number of segments that

      could call our recursive function when processing a request is 4.


      So, only O(log n) running time.
                  League of Programmers   Segment Trees
Segment Trees
                            Problems

Implementation
  Renewal Request




                 League of Programmers   Segment Trees
Segment Trees
                            Problems

Implementation
  Renewal Request
      Given an index i and the value of x. What to do?




                 League of Programmers   Segment Trees
Segment Trees
                            Problems

Implementation
  Renewal Request
      Given an index i and the value of x. What to do?
      Update the nodes in the tree so as to conform to the new
      value a[i]=x in O(log n).




                 League of Programmers   Segment Trees
Segment Trees
                            Problems

Implementation
  Renewal Request
      Given an index i and the value of x. What to do?
      Update the nodes in the tree so as to conform to the new
      value a[i]=x in O(log n).
      How many nodes and what nodes will be aected?




                 League of Programmers   Segment Trees
Segment Trees
                            Problems

Implementation
  Renewal Request
      Given an index i and the value of x. What to do?
      Update the nodes in the tree so as to conform to the new
      value a[i]=x in O(log n).
      How many nodes and what nodes will be aected?




                 League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation
  Renewal Request
      Given an index i and the value of x. What to do?
      Update the nodes in the tree so as to conform to the new
      value a[i]=x in O(log n).
      How many nodes and what nodes will be aected?
      The nodes from i th leaf node to the way upto the root of the
      tree.
      Then it is clear that the update request can be implemented as
      a recursive function: it sends the current node of the tree
      lines, and this function performs a recursive call from one of
      his two sons (the one that contains the position i in its
      segment), and after that - counts the value of the sum in the
      current node in the same way as we did in the construction of
      a tree of segments (ie, the sum of the values for the two sons
      of the current node).
                  League of Programmers   Segment Trees
Segment Trees
                            Problems

Implementation


  Problem




                 League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Problem
      You are given an array. You have queries which ask for the
      maximum element in the range l to r. And you have updates
      which increase the value of a particular element in the array
      with some value val.




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Problem
      You are given an array. You have queries which ask for the
      maximum element in the range l to r. And you have updates
      which increase the value of a particular element in the array
      with some value val.
      But seriously, how to code?




                  League of Programmers   Segment Trees
Segment Trees
                             Problems

Implementation


  Problem
      You are given an array. You have queries which ask for the
      maximum element in the range l to r. And you have updates
      which increase the value of a particular element in the array
      with some value val.
      But seriously, how to code?
      Lets look at a code




                  League of Programmers   Segment Trees
Segment Trees
                            Problems

Outline



  1   Segment Trees


  2   Problems




                 League of Programmers   Segment Trees
Segment Trees
                            Problems

Problems

  Links:
    1   http://www.spoj.pl/problems/GSS1/
    2   http://www.spoj.pl/problems/GSS3/
    3   http://www.spoj.pl/problems/HORRIBLE/
    4   http://www.spoj.pl/problems/BRCKTS/
    5   http://www.spoj.pl/problems/HELPR2D2/
    6   http://www.spoj.pl/problems/KFSTD/
    7   http://www.spoj.pl/problems/FREQUENT/
    8   http://www.spoj.pl/problems/LITE/



                 League of Programmers   Segment Trees

Mais conteúdo relacionado

Semelhante a 06 segment trees

Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
Sure Interview
 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsorts
chidabdu
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
Oye Tu
 

Semelhante a 06 segment trees (20)

Ada notes
Ada notesAda notes
Ada notes
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Segment Tree
Segment TreeSegment Tree
Segment Tree
 
Chap 5 Tree.ppt
Chap 5 Tree.pptChap 5 Tree.ppt
Chap 5 Tree.ppt
 
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic ProgammingAlgorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
Algorithm Design and Complexity - Course 4 - Heaps and Dynamic Progamming
 
Trees
TreesTrees
Trees
 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsorts
 
TeraSort
TeraSortTeraSort
TeraSort
 
5.3 dyn algo-i
5.3 dyn algo-i5.3 dyn algo-i
5.3 dyn algo-i
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Lecture 8 dynamic programming
Lecture 8 dynamic programmingLecture 8 dynamic programming
Lecture 8 dynamic programming
 
guitar chord detection
guitar chord detectionguitar chord detection
guitar chord detection
 
358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10
 
recursion tree method.pdf
recursion tree method.pdfrecursion tree method.pdf
recursion tree method.pdf
 
Module - 5_Trees.pdf
Module - 5_Trees.pdfModule - 5_Trees.pdf
Module - 5_Trees.pdf
 
Whiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in PythonWhiteboarding Coding Challenges in Python
Whiteboarding Coding Challenges in Python
 
AD3251-Data Structures Design-Notes-Tree.pdf
AD3251-Data Structures  Design-Notes-Tree.pdfAD3251-Data Structures  Design-Notes-Tree.pdf
AD3251-Data Structures Design-Notes-Tree.pdf
 
Lecture -16-merge sort (slides).pptx
Lecture -16-merge sort (slides).pptxLecture -16-merge sort (slides).pptx
Lecture -16-merge sort (slides).pptx
 
L&NDeltaTalk
L&NDeltaTalkL&NDeltaTalk
L&NDeltaTalk
 
Data structures
Data structuresData structures
Data structures
 

Mais de Pankaj Prateek

Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Pankaj Prateek
 
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Pankaj Prateek
 

Mais de Pankaj Prateek (6)

Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 2- Summer School 2014 - ACA CSE IITK
 
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITKAdvanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
Advanced CPP Lecture 1- Summer School 2014 - ACA CSE IITK
 
05 graph
05 graph05 graph
05 graph
 
04 maths
04 maths04 maths
04 maths
 
03 dp
03 dp03 dp
03 dp
 
01 basics and stl
01 basics and stl01 basics and stl
01 basics and stl
 

06 segment trees

  • 1. Segment Trees Problems Segment Trees League of Programmers ACA, IIT Kanpur League of Programmers Segment Trees
  • 2. Segment Trees Problems Outline 1 Segment Trees 2 Problems League of Programmers Segment Trees
  • 3. Segment Trees Problems A Simple Problem Problem Statement We have an array a[0 . . . n-1]. League of Programmers Segment Trees
  • 4. Segment Trees Problems A Simple Problem Problem Statement We have an array a[0 . . . n-1]. League of Programmers Segment Trees
  • 5. Segment Trees Problems A Simple Problem Problem Statement We have an array a[0 . . . n-1]. We should be able to 1 Find the sum of elements l to r League of Programmers Segment Trees
  • 6. Segment Trees Problems A Simple Problem Problem Statement We have an array a[0 . . . n-1]. We should be able to 1 Find the sum of elements l to r 2 Change in the value of a specied element of the array a[i]=x League of Programmers Segment Trees
  • 7. Segment Trees Problems A Simple Problem Possible Solutions League of Programmers Segment Trees
  • 8. Segment Trees Problems A Simple Problem Possible Solutions Naive one: Go on from l to r and keep on adding and update the element when you get a update request. Running time: O(n) to sum and O(1) to update League of Programmers Segment Trees
  • 9. Segment Trees Problems A Simple Problem Possible Solutions Naive one: Go on from l to r and keep on adding and update the element when you get a update request. Running time: O(n) to sum and O(1) to update Store sum from start to i at the i th index in an another array. Running time: O(1) to return sum, O(n) to update League of Programmers Segment Trees
  • 10. Segment Trees Problems A Simple Problem Possible Solutions Naive one: Go on from l to r and keep on adding and update the element when you get a update request. Running time: O(n) to sum and O(1) to update Store sum from start to i at the i th index in an another array. Running time: O(1) to return sum, O(n) to update This works well if the number of query operations are large and very few updates League of Programmers Segment Trees
  • 11. Segment Trees Problems A Simple Problem Possible Solutions Naive one: Go on from l to r and keep on adding and update the element when you get a update request. Running time: O(n) to sum and O(1) to update Store sum from start to i at the i th index in an another array. Running time: O(1) to return sum, O(n) to update This works well if the number of query operations are large and very few updates What if the number of query and updates are equal? League of Programmers Segment Trees
  • 12. Segment Trees Problems A Simple Problem Possible Solutions Naive one: Go on from l to r and keep on adding and update the element when you get a update request. Running time: O(n) to sum and O(1) to update Store sum from start to i at the i th index in an another array. Running time: O(1) to return sum, O(n) to update This works well if the number of query operations are large and very few updates What if the number of query and updates are equal? Can we perform both the operations in O(log n) time once given the array? League of Programmers Segment Trees
  • 13. Segment Trees Problems Segment Trees League of Programmers Segment Trees
  • 14. Segment Trees Problems Segment Trees Representation of the tree League of Programmers Segment Trees
  • 15. Segment Trees Problems Segment Trees Representation of the tree Leaf Nodes are the elements in the array. League of Programmers Segment Trees
  • 16. Segment Trees Problems Segment Trees Representation of the tree Leaf Nodes are the elements in the array. Each internal node represents some merging of the leaf nodes League of Programmers Segment Trees
  • 17. Segment Trees Problems Segment Trees Representation of the tree Leaf Nodes are the elements in the array. Each internal node represents some merging of the leaf nodes Number each node in the tree level by level League of Programmers Segment Trees
  • 18. Segment Trees Problems Segment Trees Representation of the tree Leaf Nodes are the elements in the array. Each internal node represents some merging of the leaf nodes Number each node in the tree level by level Observe that for each node the left child is 2*i and right child is 2*i+1 League of Programmers Segment Trees
  • 19. Segment Trees Problems Segment Trees Representation of the tree Leaf Nodes are the elements in the array. Each internal node represents some merging of the leaf nodes Number each node in the tree level by level Observe that for each node the left child is 2*i and right child is 2*i+1 For each node the parent is i/2 League of Programmers Segment Trees
  • 20. Segment Trees Problems Segment Trees Representation of the tree Leaf Nodes are the elements in the array. Each internal node represents some merging of the leaf nodes Number each node in the tree level by level Observe that for each node the left child is 2*i and right child is 2*i+1 For each node the parent is i/2 Just use an array to represent the tree, operate on indices to access parents and children League of Programmers Segment Trees
  • 21. Segment Trees Problems Segment Trees Representation of the tree Leaf Nodes are the elements in the array. Each internal node represents some merging of the leaf nodes Number each node in the tree level by level Observe that for each node the left child is 2*i and right child is 2*i+1 For each node the parent is i/2 Just use an array to represent the tree, operate on indices to access parents and children Note: An important feature of the tree segments is that they use linear memory: standard tree segments requires about 4n memory elements to work on an array of size n League of Programmers Segment Trees
  • 22. Segment Trees Problems Solution League of Programmers Segment Trees
  • 23. Segment Trees Problems Solution We start with a segment [0 . . . n-1]. and every time we divide the current period of two (if it has not yet become a segment of length), and then calling the same procedure on both halves, and for each such segment we store the sum on it. League of Programmers Segment Trees
  • 24. Segment Trees Problems Solution We start with a segment [0 . . . n-1]. and every time we divide the current period of two (if it has not yet become a segment of length), and then calling the same procedure on both halves, and for each such segment we store the sum on it. In other words, we calculate and remember somewhere sum of the elements of the array, ie segment a[0 . . . n-1]. Also calculate the amount of the two halves of the array: a[0 . . . n/2] and a[n/2 + 1 . . . n − 1]. Each of the two halves, in turn, divide in half and count the amount to keep them, then divide in half again, and so on until it reaches the current segment length 1 League of Programmers Segment Trees
  • 25. Segment Trees Problems Solution We start with a segment [0 . . . n-1]. and every time we divide the current period of two (if it has not yet become a segment of length), and then calling the same procedure on both halves, and for each such segment we store the sum on it. In other words, we calculate and remember somewhere sum of the elements of the array, ie segment a[0 . . . n-1]. Also calculate the amount of the two halves of the array: a[0 . . . n/2] and a[n/2 + 1 . . . n − 1]. Each of the two halves, in turn, divide in half and count the amount to keep them, then divide in half again, and so on until it reaches the current segment length 1 The number of vertices in the worst case is estimated at n + n /2 + n /4 + n /8 + · · · + 1 2 n League of Programmers Segment Trees
  • 26. Segment Trees Problems Solution We start with a segment [0 . . . n-1]. and every time we divide the current period of two (if it has not yet become a segment of length), and then calling the same procedure on both halves, and for each such segment we store the sum on it. In other words, we calculate and remember somewhere sum of the elements of the array, ie segment a[0 . . . n-1]. Also calculate the amount of the two halves of the array: a[0 . . . n/2] and a[n/2 + 1 . . . n − 1]. Each of the two halves, in turn, divide in half and count the amount to keep them, then divide in half again, and so on until it reaches the current segment length 1 The number of vertices in the worst case is estimated at n + n /2 + n /4 + n /8 + · · · + 1 2 n The height of the tree is the value of the segments O(log n). League of Programmers Segment Trees
  • 27. Segment Trees Problems Implementation Building the tree League of Programmers Segment Trees
  • 28. Segment Trees Problems Implementation Building the tree From the bottom up: rst write the values of the elements a[i] the corresponding leaves of the tree, then on the basis of these values to calculate the nodes of the previous level as the sum of the two leaves, then similarly calculate values for one more level, etc. Convenient to describe the operation recursively. League of Programmers Segment Trees
  • 29. Segment Trees Problems Implementation Building the tree From the bottom up: rst write the values of the elements a[i] the corresponding leaves of the tree, then on the basis of these values to calculate the nodes of the previous level as the sum of the two leaves, then similarly calculate values for one more level, etc. Convenient to describe the operation recursively. Time to do this? League of Programmers Segment Trees
  • 30. Segment Trees Problems Implementation Building the tree From the bottom up: rst write the values of the elements a[i] the corresponding leaves of the tree, then on the basis of these values to calculate the nodes of the previous level as the sum of the two leaves, then similarly calculate values for one more level, etc. Convenient to describe the operation recursively. Time to do this? League of Programmers Segment Trees
  • 31. Segment Trees Problems Implementation Building the tree From the bottom up: rst write the values of the elements a[i] the corresponding leaves of the tree, then on the basis of these values to calculate the nodes of the previous level as the sum of the two leaves, then similarly calculate values for one more level, etc. Convenient to describe the operation recursively. Time to do this? O(n) since each node in the tree is modied once and uses only a max of 2 nodes (already computed) for computation. League of Programmers Segment Trees
  • 32. Segment Trees Problems Implementation Query Request League of Programmers Segment Trees
  • 33. Segment Trees Problems Implementation Query Request The input is two numbers l and r. And we have the time O (logn). Calculate the sum of the segment a[l . . . r ] . League of Programmers Segment Trees
  • 34. Segment Trees Problems Implementation Query Request The input is two numbers l and r. And we have the time O (logn). Calculate the sum of the segment a[l . . . r ] . Can be done recursively League of Programmers Segment Trees
  • 35. Segment Trees Problems Implementation Query Request The input is two numbers l and r. And we have the time O (logn). Calculate the sum of the segment a[l . . . r ] . Can be done recursively If your range is within the segment completely, return the value at that node League of Programmers Segment Trees
  • 36. Segment Trees Problems Implementation Query Request The input is two numbers l and r. And we have the time O (logn). Calculate the sum of the segment a[l . . . r ] . Can be done recursively If your range is within the segment completely, return the value at that node If its completely out of range, return 0 or null League of Programmers Segment Trees
  • 37. Segment Trees Problems Implementation Query Request The input is two numbers l and r. And we have the time O (logn). Calculate the sum of the segment a[l . . . r ] . Can be done recursively If your range is within the segment completely, return the value at that node If its completely out of range, return 0 or null If its in one of the child, query on that child League of Programmers Segment Trees
  • 38. Segment Trees Problems Implementation Query Request The input is two numbers l and r. And we have the time O (logn). Calculate the sum of the segment a[l . . . r ] . Can be done recursively If your range is within the segment completely, return the value at that node If its completely out of range, return 0 or null If its in one of the child, query on that child If its in both the child, do query on both of them League of Programmers Segment Trees
  • 39. Segment Trees Problems Implementation Query Request Pseudocode query(node,l,r) { if range of node is within l and r return value in node else if range of node is completely outside l and r return 0 else return sum(query(left-child,l,r),query(right-child,l,r)) } League of Programmers Segment Trees
  • 40. Segment Trees Problems Implementation Query Request Pseudocode query(node,l,r) { if range of node is within l and r return value in node else if range of node is completely outside l and r return 0 else return sum(query(left-child,l,r),query(right-child,l,r)) } But this doesn't look O(log n) League of Programmers Segment Trees
  • 41. Segment Trees Problems Implementation Query Request Pseudocode query(node,l,r) { if range of node is within l and r return value in node else if range of node is completely outside l and r return 0 else return sum(query(left-child,l,r),query(right-child,l,r)) } But this doesn't look O(log n) It is. At any level of the tree, the maximum number of segments that could call our recursive function when processing a request is 4. League of Programmers Segment Trees
  • 42. Segment Trees Problems Implementation Query Request Pseudocode query(node,l,r) { if range of node is within l and r return value in node else if range of node is completely outside l and r return 0 else return sum(query(left-child,l,r),query(right-child,l,r)) } But this doesn't look O(log n) It is. At any level of the tree, the maximum number of segments that could call our recursive function when processing a request is 4. So, only O(log n) running time. League of Programmers Segment Trees
  • 43. Segment Trees Problems Implementation Renewal Request League of Programmers Segment Trees
  • 44. Segment Trees Problems Implementation Renewal Request Given an index i and the value of x. What to do? League of Programmers Segment Trees
  • 45. Segment Trees Problems Implementation Renewal Request Given an index i and the value of x. What to do? Update the nodes in the tree so as to conform to the new value a[i]=x in O(log n). League of Programmers Segment Trees
  • 46. Segment Trees Problems Implementation Renewal Request Given an index i and the value of x. What to do? Update the nodes in the tree so as to conform to the new value a[i]=x in O(log n). How many nodes and what nodes will be aected? League of Programmers Segment Trees
  • 47. Segment Trees Problems Implementation Renewal Request Given an index i and the value of x. What to do? Update the nodes in the tree so as to conform to the new value a[i]=x in O(log n). How many nodes and what nodes will be aected? League of Programmers Segment Trees
  • 48. Segment Trees Problems Implementation Renewal Request Given an index i and the value of x. What to do? Update the nodes in the tree so as to conform to the new value a[i]=x in O(log n). How many nodes and what nodes will be aected? The nodes from i th leaf node to the way upto the root of the tree. Then it is clear that the update request can be implemented as a recursive function: it sends the current node of the tree lines, and this function performs a recursive call from one of his two sons (the one that contains the position i in its segment), and after that - counts the value of the sum in the current node in the same way as we did in the construction of a tree of segments (ie, the sum of the values for the two sons of the current node). League of Programmers Segment Trees
  • 49. Segment Trees Problems Implementation Problem League of Programmers Segment Trees
  • 50. Segment Trees Problems Implementation Problem You are given an array. You have queries which ask for the maximum element in the range l to r. And you have updates which increase the value of a particular element in the array with some value val. League of Programmers Segment Trees
  • 51. Segment Trees Problems Implementation Problem You are given an array. You have queries which ask for the maximum element in the range l to r. And you have updates which increase the value of a particular element in the array with some value val. But seriously, how to code? League of Programmers Segment Trees
  • 52. Segment Trees Problems Implementation Problem You are given an array. You have queries which ask for the maximum element in the range l to r. And you have updates which increase the value of a particular element in the array with some value val. But seriously, how to code? Lets look at a code League of Programmers Segment Trees
  • 53. Segment Trees Problems Outline 1 Segment Trees 2 Problems League of Programmers Segment Trees
  • 54. Segment Trees Problems Problems Links: 1 http://www.spoj.pl/problems/GSS1/ 2 http://www.spoj.pl/problems/GSS3/ 3 http://www.spoj.pl/problems/HORRIBLE/ 4 http://www.spoj.pl/problems/BRCKTS/ 5 http://www.spoj.pl/problems/HELPR2D2/ 6 http://www.spoj.pl/problems/KFSTD/ 7 http://www.spoj.pl/problems/FREQUENT/ 8 http://www.spoj.pl/problems/LITE/ League of Programmers Segment Trees