logo

Binært indeksert tre: Range Update og Range Queries

Gitt en matrise arr[0..N-1]. Følgende operasjoner må utføres. 

  1. oppdatering(l r val) : Legg til 'val' til alle elementene i matrisen fra [l r].
  2. getRangeSum(l r) : Finn summen av alle elementene i matrisen fra [l r].

Til å begynne med er alle elementene i matrisen 0. Spørringer kan være i hvilken som helst rekkefølge, dvs. det kan være mange oppdateringer før områdesummen.



Eksempel:

Inndata: N = 5   // {0 0 0 0 0}
Forespørsler: oppdatering: l = 0 r = 4 val = 2
               oppdatering: l = 3 r = 4 val = 3 
               getRangeSum : l = 2 r = 4

Produksjon: Summen av elementene i området [2 4] er 12
Forklaring: Array etter første oppdatering blir {2 2 2 2 2}
Array etter andre oppdatering blir {2 2 2 5 5}



Naiv tilnærming: Følg ideen nedenfor for å løse problemet:

I forrige innlegg vi diskuterte rekkeviddeoppdatering og punktspørringsløsninger ved bruk av BIT. 
rangeUpdate(l r val) : Vi legger til 'val' til elementet ved indeks 'l'. Vi trekker 'val' fra elementet ved indeks 'r+1'. 
getElement(indeks) [eller getSum()]: Vi returnerer summen av elementer fra 0 til indeks som raskt kan fås ved hjelp av BIT.
Vi kan beregne rangeSum() ved å bruke getSum()-spørringer. 
rangeSum(l r) = getSum(r) - getSum(l-1)

justere bilder i css

En enkel løsning er å bruke løsningene som er omtalt i forrige innlegg . Spørsmålet om oppdatering av område er det samme. Rangesum-spørring kan oppnås ved å gjøre en get-spørring for alle elementene i området. 



Effektiv tilnærming: Følg ideen nedenfor for å løse problemet:

Vi får avstandssum ved bruk av prefikssummer. Hvordan sikre at oppdateringen gjøres på en måte slik at prefikssum kan gjøres raskt? Tenk på en situasjon der prefikssum [0 k] (hvor 0<= k < n) is needed after range update on the range [l r]. Three cases arise as k can possibly lie in 3 regions.

  • Sak 1 : 0< k < l 
    • Oppdateringsspørringen vil ikke påvirke sumspørringen.
  • Tilfelle 2 : l<= k <= r 
    • Tenk på et eksempel:  Legg til 2 til området [2 4] den resulterende matrisen vil være: 0 0 2 2 2
      Hvis k = 3 Summen fra [0 k] = 4

Hvordan få dette resultatet? 
Bare legg til val fra lthindeks til kthindeks. Summen økes med 'val*(k) - val*(l-1)' etter oppdateringsspørringen. 

  • Tilfelle 3 : k > r 
    • For dette tilfellet må vi legge til 'val' fra lthindeks til rthindeks. Summen økes med 'val*r – val*(l-1)' på grunn av en oppdateringsforespørsel.

Observasjoner:  

Tilfelle 1: er enkel siden summen ville forbli den samme som den var før oppdateringen.

Tilfelle 2: Summen ble økt med val*k - val*(l-1). Vi kan finne 'val' det ligner på å finne ithelement i områdeoppdatering og punktsøkingsartikkel . Så vi opprettholder én BIT for Range Update og Point Queries, denne BIT vil være nyttig for å finne verdien på kthindeks. Nå beregnes val * k hvordan man håndterer ekstraledd val*(l-1)? 
For å håndtere denne ekstra termen opprettholder vi en annen BIT (BIT2). Oppdater val * (l-1) klthindeks, slik at når getSum-spørringen utføres på BIT2 vil resultatet gis som val*(l-1).

Tilfelle 3: Summen i tilfelle 3 ble økt med 'val*r - val *(l-1)' verdien av denne termen kan oppnås ved å bruke BIT2. I stedet for å legge til trekker vi 'val*(l-1) - val*r', da vi kan få denne verdien fra BIT2 ved å legge til val*(l-1) som vi gjorde i tilfelle 2 og trekke fra val*r i hver oppdateringsoperasjon.

Oppdater spørring 

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

Range Sum 

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

romertall 1-100

Følg trinnene nedenfor for å løse problemet:

  • Lag de to binære indekstrærne ved å bruke den gitte funksjonen constructBITree()
  • For å finne summen i et gitt område kall funksjonen rangeSum() med parametere som gitt område og binært indekserte trær
    • Anrop en funksjonssum som vil returnere en sum i området [0 X]
    • Retursum(R) - sum(L-1)
      • Inne i denne funksjonen kaller funksjonen getSum() som vil returnere summen av matrisen fra [0 X]
      • Returner getSum(Tre1 x) * x - getSum(tre2 x)
      • Inne i getSum()-funksjonen lag en heltallssum lik null og øk indeksen med 1
      • Mens indeksen er større enn null, øk summen med Tre[indeks]
      • Reduser indeksen med (indeks & (-indeks)) for å flytte indeksen til overordnet node i treet
      • Retursum
  • Skriv ut summen i det gitte området

Nedenfor er implementeringen av tilnærmingen ovenfor: 

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>

Produksjon
Sum of elements from [14] is 50

Tidskompleksitet : O(q * log(N)) hvor q er antall spørringer.
Hjelpeplass: PÅ)