logo

Binaire geïndexeerde boom: bereikupdate en bereikquery's

Gegeven een array arr[0..N-1]. De volgende handelingen moeten worden uitgevoerd. 

  1. update(l r val) : Voeg ‘val’ toe aan alle elementen in de array van [l r].
  2. getRangeSum(l r) : Vind de som van alle elementen in de array uit [l r].

Aanvankelijk zijn alle elementen in de array 0. Zoekopdrachten kunnen in elke volgorde staan, dat wil zeggen dat er veel updates kunnen plaatsvinden vóór de bereiksom.



Voorbeeld:

Invoer: N = 5   // {0 0 0 0 0}
Vragen: update: l = 0 r = 4 val = 2
               update: l = 3 r = 4 val = 3 
               getRangeSom: l = 2 r = 4

Uitgang: De som van de elementen van bereik [2 4] is 12
Uitleg: Array na eerste update wordt {2 2 2 2 2}
Array na tweede update wordt {2 2 2 5 5}



Naïeve aanpak: Om het probleem op te lossen, volgt u het onderstaande idee:

In de vorig bericht we bespraken oplossingen voor bereikupdates en puntquery's met behulp van BIT. 
rangeUpdate(l r val) : We voegen 'val' toe aan het element bij index 'l'. We trekken 'val' af van het element bij index 'r+1'. 
getElement(index) [of getSum()]: We retourneren de som van elementen van 0 tot index, die snel kan worden verkregen met behulp van BIT.
We kunnen rangeSum() berekenen met behulp van getSum()-query's. 
bereikSom(l r) = getSom(r) - getSom(l-1)

datum opmaken naar string

Een eenvoudige oplossing is om de oplossingen te gebruiken die worden besproken in de vorig bericht . De zoekopdracht voor het bijwerken van het bereik is hetzelfde. De bereiksomquery kan worden bereikt door een get-query uit te voeren voor alle elementen in het bereik. 



Efficiënte aanpak: Om het probleem op te lossen, volgt u het onderstaande idee:

We krijgen de bereiksom met behulp van voorvoegselsommen. Hoe zorg ik ervoor dat de update zo wordt uitgevoerd dat de prefixsom snel kan worden uitgevoerd? Beschouw een situatie waarin het voorvoegsel som [0 k] (waarbij 0<= k < n) is needed after range update on the range [l r]. Three cases arise as k can possibly lie in 3 regions.

  • Geval 1 : 0< k < l 
    • De updatequery heeft geen invloed op de somquery.
  • Geval 2 : l<= k <= r 
    • Beschouw een voorbeeld: Voeg 2 toe aan bereik [2 4] en de resulterende array zou zijn: 0 0 2 2 2
      Als k = 3 De som van [0 k] = 4

Hoe dit resultaat te verkrijgen? 
Voeg eenvoudig de val van l toeeindex naar keindex. De som wordt na de updatequery verhoogd met 'val*(k) - val*(l-1)'. 

  • Geval 3 : k > r 
    • Voor dit geval moeten we 'val' uit l toevoegeneindex naar reindex. De som wordt verhoogd met 'val*r – val*(l-1)' vanwege een updatequery.

Observaties:  

Geval 1: is eenvoudig omdat de som hetzelfde zou blijven als vóór de update.

Geval 2: De som werd verhoogd met val*k - val*(l-1). We kunnen 'val' vinden, het is vergelijkbaar met het vinden van de ieelement erin bereikupdate en puntqueryartikel . We onderhouden dus één BIT voor bereikupdates en puntquery's. Deze BIT zal nuttig zijn bij het vinden van de waarde op keindex. Nu wordt val * k berekend, hoe moet omgegaan worden met de extra term val*(l-1)? 
Om deze extra termijn te kunnen verwerken hanteren wij nog een BIT (BIT2). Update val * (l-1) op leindex, dus wanneer de getSum-query wordt uitgevoerd op BIT2, zal het resultaat val*(l-1) opleveren.

Geval 3: De som in geval 3 werd verhoogd met 'val*r - val *(l-1)'. De waarde van deze term kan worden verkregen met behulp van BIT2. In plaats van op te tellen trekken we 'val*(l-1) - val*r' af, omdat we deze waarde uit BIT2 kunnen halen door val*(l-1) toe te voegen zoals we deden in geval 2 en val*r af te trekken bij elke updatebewerking.

Java-variabele variabele

Zoekopdracht bijwerken 

Update(BITree1 l val)
Bijwerken(BITree1 r+1 -val)
UpdateBIT2(BITree2 l val*(l-1))
UpdateBIT2(BITree2 r+1 -val*r)

Bereik som 

getSum(BITTree1 k) *k) - getSum(BITTree2 k)

Volg de onderstaande stappen om het probleem op te lossen:

  • Creëer de twee binaire indexbomen met behulp van de gegeven functie constructBITree()
  • Om de som in een bepaald bereik te vinden, roept u de functie rangeSum() aan met parameters als het gegeven bereik en binair geïndexeerde bomen
    • Roep een functie som aan die een som in het bereik [0 X] retourneert
    • Retoursom(R) - som(L-1)
      • Roep binnen deze functie de functie getSum() aan, die de som van de array van [0 X] retourneert
      • Retourneert getSum(Boom1 x) * x - getSum(boom2 x)
      • Maak binnen de functie getSum() een gehele som gelijk aan nul en verhoog de index met 1
      • Terwijl de index groter is dan nul, verhoog je de som met Tree[index]
      • Verlaag de index met (index & (-index)) om de index naar het bovenliggende knooppunt in de boom te verplaatsen
      • Retoursom
  • Druk de som binnen het opgegeven bereik af

Hieronder vindt u de implementatie van de bovenstaande aanpak: 

C++
// C++ program to demonstrate Range Update // and Range Queries using BIT #include    using namespace std; // Returns sum of arr[0..index]. This function assumes // that the array is preprocessed and partial sums of // array elements are stored in BITree[] int getSum(int BITree[] int index) {  int sum = 0; // Initialize result  // index in BITree[] is 1 more than the index in arr[]  index = index + 1;  // Traverse ancestors of BITree[index]  while (index > 0) {  // Add current element of BITree to sum  sum += BITree[index];  // Move index to parent node in getSum View  index -= index & (-index);  }  return sum; } // Updates a node in Binary Index Tree (BITree) at given // index in BITree. The given value 'val' is added to // BITree[i] and all of its ancestors in tree. void updateBIT(int BITree[] int n int index int val) {  // index in BITree[] is 1 more than the index in arr[]  index = index + 1;  // Traverse all ancestors and add 'val'  while (index <= n) {  // Add 'val' to current node of BI Tree  BITree[index] += val;  // Update index to that of parent in update View  index += index & (-index);  } } // Returns the sum of array from [0 x] int sum(int x int BITTree1[] int BITTree2[]) {  return (getSum(BITTree1 x) * x) - getSum(BITTree2 x); } void updateRange(int BITTree1[] int BITTree2[] int n  int val int l int r) {  // Update Both the Binary Index Trees  // As discussed in the article  // Update BIT1  updateBIT(BITTree1 n l val);  updateBIT(BITTree1 n r + 1 -val);  // Update BIT2  updateBIT(BITTree2 n l val * (l - 1));  updateBIT(BITTree2 n r + 1 -val * r); } int rangeSum(int l int r int BITTree1[] int BITTree2[]) {  // Find sum from [0r] then subtract sum  // from [0l-1] in order to find sum from  // [lr]  return sum(r BITTree1 BITTree2)  - sum(l - 1 BITTree1 BITTree2); } int* constructBITree(int n) {  // Create and initialize BITree[] as 0  int* BITree = new int[n + 1];  for (int i = 1; i <= n; i++)  BITree[i] = 0;  return BITree; } // Driver code int main() {  int n = 5;  // Construct two BIT  int *BITTree1 *BITTree2;  // BIT1 to get element at any index  // in the array  BITTree1 = constructBITree(n);  // BIT 2 maintains the extra term  // which needs to be subtracted  BITTree2 = constructBITree(n);  // Add 5 to all the elements from [04]  int l = 0 r = 4 val = 5;  updateRange(BITTree1 BITTree2 n val l r);  // Add 10 to all the elements from [24]  l = 2 r = 4 val = 10;  updateRange(BITTree1 BITTree2 n val l r);  // Find sum of all the elements from  // [14]  l = 1 r = 4;  cout << 'Sum of elements from [' << l << '' << r  << '] is ';  cout << rangeSum(l r BITTree1 BITTree2) << 'n';  return 0; } 
Java
// Java program to demonstrate Range Update // and Range Queries using BIT import java.util.*; class GFG {  // Returns sum of arr[0..index]. This function assumes  // that the array is preprocessed and partial sums of  // array elements are stored in BITree[]  static int getSum(int BITree[] int index)  {  int sum = 0; // Initialize result  // index in BITree[] is 1 more than the index in  // arr[]  index = index + 1;  // Traverse ancestors of BITree[index]  while (index > 0) {  // Add current element of BITree to sum  sum += BITree[index];  // Move index to parent node in getSum View  index -= index & (-index);  }  return sum;  }  // Updates a node in Binary Index Tree (BITree) at given  // index in BITree. The given value 'val' is added to  // BITree[i] and all of its ancestors in tree.  static void updateBIT(int BITree[] int n int index  int val)  {  // index in BITree[] is 1 more than the index in  // arr[]  index = index + 1;  // Traverse all ancestors and add 'val'  while (index <= n) {  // Add 'val' to current node of BI Tree  BITree[index] += val;  // Update index to that of parent in update View  index += index & (-index);  }  }  // Returns the sum of array from [0 x]  static int sum(int x int BITTree1[] int BITTree2[])  {  return (getSum(BITTree1 x) * x)  - getSum(BITTree2 x);  }  static void updateRange(int BITTree1[] int BITTree2[]  int n int val int l int r)  {  // Update Both the Binary Index Trees  // As discussed in the article  // Update BIT1  updateBIT(BITTree1 n l val);  updateBIT(BITTree1 n r + 1 -val);  // Update BIT2  updateBIT(BITTree2 n l val * (l - 1));  updateBIT(BITTree2 n r + 1 -val * r);  }  static int rangeSum(int l int r int BITTree1[]  int BITTree2[])  {  // Find sum from [0r] then subtract sum  // from [0l-1] in order to find sum from  // [lr]  return sum(r BITTree1 BITTree2)  - sum(l - 1 BITTree1 BITTree2);  }  static int[] constructBITree(int n)  {  // Create and initialize BITree[] as 0  int[] BITree = new int[n + 1];  for (int i = 1; i <= n; i++)  BITree[i] = 0;  return BITree;  }  // Driver Program to test above function  public static void main(String[] args)  {  int n = 5;  // Contwo BIT  int[] BITTree1;  int[] BITTree2;  // BIT1 to get element at any index  // in the array  BITTree1 = constructBITree(n);  // BIT 2 maintains the extra term  // which needs to be subtracted  BITTree2 = constructBITree(n);  // Add 5 to all the elements from [04]  int l = 0 r = 4 val = 5;  updateRange(BITTree1 BITTree2 n val l r);  // Add 10 to all the elements from [24]  l = 2;  r = 4;  val = 10;  updateRange(BITTree1 BITTree2 n val l r);  // Find sum of all the elements from  // [14]  l = 1;  r = 4;  System.out.print('Sum of elements from [' + l + ''  + r + '] is ');  System.out.print(rangeSum(l r BITTree1 BITTree2)  + 'n');  } } // This code is contributed by 29AjayKumar 
Python3
# Python3 program to demonstrate Range Update # and Range Queries using BIT # Returns sum of arr[0..index]. This function assumes # that the array is preprocessed and partial sums of # array elements are stored in BITree[] def getSum(BITree: list index: int) -> int: summ = 0 # Initialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while index > 0: # Add current element of BITree to sum summ += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return summ # Updates a node in Binary Index Tree (BITree) at given # index in BITree. The given value 'val' is added to # BITree[i] and all of its ancestors in tree. def updateBit(BITTree: list n: int index: int val: int) -> None: # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while index <= n: # Add 'val' to current node of BI Tree BITTree[index] += val # Update index to that of parent in update View index += index & (-index) # Returns the sum of array from [0 x] def summation(x: int BITTree1: list BITTree2: list) -> int: return (getSum(BITTree1 x) * x) - getSum(BITTree2 x) def updateRange(BITTree1: list BITTree2: list n: int val: int l: int r: int) -> None: # Update Both the Binary Index Trees # As discussed in the article # Update BIT1 updateBit(BITTree1 n l val) updateBit(BITTree1 n r + 1 -val) # Update BIT2 updateBit(BITTree2 n l val * (l - 1)) updateBit(BITTree2 n r + 1 -val * r) def rangeSum(l: int r: int BITTree1: list BITTree2: list) -> int: # Find sum from [0r] then subtract sum # from [0l-1] in order to find sum from # [lr] return summation(r BITTree1 BITTree2) - summation( l - 1 BITTree1 BITTree2) # Driver Code if __name__ == '__main__': n = 5 # BIT1 to get element at any index # in the array BITTree1 = [0] * (n + 1) # BIT 2 maintains the extra term # which needs to be subtracted BITTree2 = [0] * (n + 1) # Add 5 to all the elements from [04] l = 0 r = 4 val = 5 updateRange(BITTree1 BITTree2 n val l r) # Add 10 to all the elements from [24] l = 2 r = 4 val = 10 updateRange(BITTree1 BITTree2 n val l r) # Find sum of all the elements from # [14] l = 1 r = 4 print('Sum of elements from [%d%d] is %d' % (l r rangeSum(l r BITTree1 BITTree2))) # This code is contributed by # sanjeev2552 
C#
// C# program to demonstrate Range Update // and Range Queries using BIT using System; class GFG {  // Returns sum of arr[0..index]. This function assumes  // that the array is preprocessed and partial sums of  // array elements are stored in BITree[]  static int getSum(int[] BITree int index)  {  int sum = 0; // Initialize result  // index in BITree[] is 1 more than  // the index in []arr  index = index + 1;  // Traverse ancestors of BITree[index]  while (index > 0) {  // Add current element of BITree to sum  sum += BITree[index];  // Move index to parent node in getSum View  index -= index & (-index);  }  return sum;  }  // Updates a node in Binary Index Tree (BITree) at given  // index in BITree. The given value 'val' is added to  // BITree[i] and all of its ancestors in tree.  static void updateBIT(int[] BITree int n int index  int val)  {  // index in BITree[] is 1 more than  // the index in []arr  index = index + 1;  // Traverse all ancestors and add 'val'  while (index <= n) {  // Add 'val' to current node of BI Tree  BITree[index] += val;  // Update index to that of  // parent in update View  index += index & (-index);  }  }  // Returns the sum of array from [0 x]  static int sum(int x int[] BITTree1 int[] BITTree2)  {  return (getSum(BITTree1 x) * x)  - getSum(BITTree2 x);  }  static void updateRange(int[] BITTree1 int[] BITTree2  int n int val int l int r)  {  // Update Both the Binary Index Trees  // As discussed in the article  // Update BIT1  updateBIT(BITTree1 n l val);  updateBIT(BITTree1 n r + 1 -val);  // Update BIT2  updateBIT(BITTree2 n l val * (l - 1));  updateBIT(BITTree2 n r + 1 -val * r);  }  static int rangeSum(int l int r int[] BITTree1  int[] BITTree2)  {  // Find sum from [0r] then subtract sum  // from [0l-1] in order to find sum from  // [lr]  return sum(r BITTree1 BITTree2)  - sum(l - 1 BITTree1 BITTree2);  }  static int[] constructBITree(int n)  {  // Create and initialize BITree[] as 0  int[] BITree = new int[n + 1];  for (int i = 1; i <= n; i++)  BITree[i] = 0;  return BITree;  }  // Driver Code  public static void Main(String[] args)  {  int n = 5;  // Contwo BIT  int[] BITTree1;  int[] BITTree2;  // BIT1 to get element at any index  // in the array  BITTree1 = constructBITree(n);  // BIT 2 maintains the extra term  // which needs to be subtracted  BITTree2 = constructBITree(n);  // Add 5 to all the elements from [04]  int l = 0 r = 4 val = 5;  updateRange(BITTree1 BITTree2 n val l r);  // Add 10 to all the elements from [24]  l = 2;  r = 4;  val = 10;  updateRange(BITTree1 BITTree2 n val l r);  // Find sum of all the elements from  // [14]  l = 1;  r = 4;  Console.Write('Sum of elements from [' + l + '' + r  + '] is ');  Console.Write(rangeSum(l r BITTree1 BITTree2)  + 'n');  } } // This code is contributed by 29AjayKumar 
JavaScript
<script> // JavaScript program to demonstrate Range Update // and Range Queries using BIT // Returns sum of arr[0..index]. This function assumes // that the array is preprocessed and partial sums of // array elements are stored in BITree[] function getSum(BITreeindex) {  let sum = 0; // Initialize result    // index in BITree[] is 1 more than the index in arr[]  index = index + 1;    // Traverse ancestors of BITree[index]  while (index > 0)  {  // Add current element of BITree to sum  sum += BITree[index];    // Move index to parent node in getSum View  index -= index & (-index);  }  return sum; } // Updates a node in Binary Index Tree (BITree) at given // index in BITree. The given value 'val' is added to // BITree[i] and all of its ancestors in tree. function updateBIT(BITreenindexval) {  // index in BITree[] is 1 more than the index in arr[]  index = index + 1;    // Traverse all ancestors and add 'val'  while (index <= n)  {  // Add 'val' to current node of BI Tree  BITree[index] += val;    // Update index to that of parent in update View  index += index & (-index);  } } // Returns the sum of array from [0 x] function sum(xBITTree1BITTree2) {  return (getSum(BITTree1 x) * x) - getSum(BITTree2 x); } function updateRange(BITTree1BITTree2nvallr) {  // Update Both the Binary Index Trees  // As discussed in the article    // Update BIT1  updateBIT(BITTree1 n l val);  updateBIT(BITTree1 n r + 1 -val);    // Update BIT2  updateBIT(BITTree2 n l val * (l - 1));  updateBIT(BITTree2 n r + 1 -val * r); } function rangeSum(lrBITTree1BITTree2) {  // Find sum from [0r] then subtract sum  // from [0l-1] in order to find sum from  // [lr]  return sum(r BITTree1 BITTree2) -  sum(l - 1 BITTree1 BITTree2); } function constructBITree(n) {  // Create and initialize BITree[] as 0  let BITree = new Array(n + 1);  for (let i = 1; i <= n; i++)  BITree[i] = 0;    return BITree; } // Driver Program to test above function let n = 5;   // Contwo BIT let BITTree1; let BITTree2; // BIT1 to get element at any index // in the array BITTree1 = constructBITree(n); // BIT 2 maintains the extra term // which needs to be subtracted BITTree2 = constructBITree(n); // Add 5 to all the elements from [04] let l = 0  r = 4  val = 5; updateRange(BITTree1 BITTree2 n val l r); // Add 10 to all the elements from [24] l = 2 ; r = 4 ; val = 10; updateRange(BITTree1 BITTree2 n val l r); // Find sum of all the elements from // [14] l = 1 ; r = 4; document.write('Sum of elements from [' + l  + '' + r+ '] is '); document.write(rangeSum(l r BITTree1 BITTree2)+ '  
'
); // This code is contributed by rag2127 </script>

Uitvoer
Sum of elements from [14] is 50

Tijdcomplexiteit : O(q * log(N)) waarbij q het aantal zoekopdrachten is.
Hulpruimte: OP)