Adott egy tömb arr[0..N-1]. A következő műveleteket kell végrehajtani.
- frissítés (l r val) : Adja hozzá a „val”-t a tömb összes eleméhez [l r]-ből.
- getRangeSum(l r) : Keresse meg a tömb összes elemének összegét [l r]-ből.
Kezdetben a tömb összes eleme 0. A lekérdezések tetszőleges sorrendben lehetnek, azaz sok frissítés történhet a tartomány összege előtt.
Példa:
Bemenet: N = 5 // {0 0 0 0 0}
Lekérdezések: frissítés: l = 0 r = 4 val = 2
frissítés: l = 3 r = 4 val = 3
getRangeSum : l = 2 r = 4Kimenet: A [2 4] tartomány elemeinek összege 12
Magyarázat: A tömb az első frissítés után a következő lesz: {2 2 2 2 2}
A tömb a második frissítés után a következő lesz: {2 2 2 5 5}
Naiv megközelítés: A probléma megoldásához kövesse az alábbi ötletet:
A előző bejegyzés a tartományfrissítési és pontlekérdezési megoldásokat tárgyaltuk a BIT használatával.
rangeUpdate(l r val) : Az 'l' indexű elemhez hozzáadjuk a 'val'-t. Kivonjuk a 'val'-t az 'r+1' indexű elemből.
getElement(index) [vagy getSum()]: Az elemek összegét 0-tól indexre adjuk vissza, amely BIT segítségével gyorsan megkapható.
A rangeSum() értéket a getSum() lekérdezések segítségével tudjuk kiszámítani.
rangeSum(l r) = getSum(r) - getSum(l-1)analóg kommunikációEgyszerű megoldás pontban tárgyalt megoldásokat kell használni előző bejegyzés . A tartományfrissítési lekérdezés ugyanaz. A tartomány összegének lekérdezése a tartomány összes elemére vonatkozó get lekérdezéssel érhető el.
Hatékony megközelítés: A probléma megoldásához kövesse az alábbi ötletet:
A tartomány összegét előtagösszegekkel kapjuk meg. Hogyan lehet meggyőződni arról, hogy a frissítés úgy történik, hogy az előtag összegét gyorsan meg lehessen tenni? Tekintsünk egy olyan helyzetet, ahol az előtag összege [0 k] (ahol 0<= k < n) is needed after range update on the range [l r]. Three cases arise as k can possibly lie in 3 regions.
- 1. eset : 0< k < l
- A frissítési lekérdezés nincs hatással az összeg lekérdezésre.
- 2. eset : l<= k <= r
- Vegyünk egy példát: Adjon hozzá 2-t a [2 4] tartományhoz, az eredményül kapott tömb a következő lesz: 0 0 2 2 2
Ha k = 3, a [0 k] = 4 összegeHogyan lehet elérni ezt az eredményt?
Egyszerűen adja hozzá a val értéket l-bőlthindex a kthindex. Az összeg a frissítési lekérdezés után 'val*(k) - val*(l-1)' értékkel növekszik.
- 3. eset : k > r
- Ebben az esetben hozzá kell adnunk a „val”-t az l-bőlthindex az rthindex. Az összeg egy frissítési lekérdezés miatt 'val*r – val*(l-1)'-vel növekszik.
Észrevételek:
1. eset: egyszerű, mivel az összeg ugyanaz marad, mint a frissítés előtt.
2. eset: Az összeget val*k - val*(l-1) értékkel növeltük. Megtalálhatjuk a 'val'-t, ez hasonló az i-hezthelem be tartományfrissítés és pontlekérdezés cikk . Tehát egy BIT-et tartunk fenn a tartományfrissítéshez és a pontlekérdezésekhez, ez a BIT hasznos lesz a k érték megtalálásábanthindex. Most a val * k kiszámítása, hogyan kell kezelni a val*(l-1) extra kifejezést?
Ennek az extra kifejezésnek a kezelésére egy másik BIT-et (BIT2) tartunk fenn. Val * (l-1) frissítése lthindexet, így amikor a getSum lekérdezést végrehajtják a BIT2-n, az eredmény a következő: val*(l-1).
3. eset: A 3. esetben az összeget 'val*r - val *(l-1)'-vel növeltük, ennek a tagnak az értéke a BIT2 segítségével kapható meg. Az összeadás helyett kivonjuk a 'val*(l-1) - val*r'-t, mivel ezt az értéket a BIT2-ből úgy kaphatjuk meg, ha hozzáadjuk a val*(l-1) értéket, ahogy a 2. esetben tettük, és minden frissítési műveletnél kivonjuk a val*r-t.
Lekérdezés frissítése
Frissítés (BITree1 l érték)
Frissítés (BITree1 r+1 -val)
FrissítésBIT2(BITree2 l val*(l-1))
FrissítésBIT2(BITree2 r+1 -val*r)térkép javaTartomány összege
getSum(BITTree1 k) *k) - getSum(BITTree2 k)
A probléma megoldásához kövesse az alábbi lépéseket:
- Hozza létre a két bináris indexfát a megadott constructBITree() függvény segítségével
- Az összeg meghatározásához egy adott tartományban hívja meg a rangeSum() függvényt a megadott tartomány paramétereivel és binárisan indexelt fákkal
- Hívjon egy összeg függvényt, amely a [0 X] tartományba eső összeget adja vissza
- Visszatérési összeg(R) – összeg(L-1)
- Ezen a függvényen belül hívja meg a getSum() függvényt, amely a [0 X] tömb összegét adja vissza
- Return getSum(Tree1 x) * x - getSum(fa2 x)
- A getSum() függvényen belül hozzon létre egy nullával egyenlő egész összeget, és növelje az indexet 1-gyel
- Amíg az index nagyobb nullánál, növelje az összeget a Tree[index] értékkel
- Csökkentse az indexet az (index & (-index)) értékkel, hogy áthelyezze az indexet a fa szülőcsomópontjára
- Visszatérő összeg
- Nyomtassa ki az összeget a megadott tartományban
Az alábbiakban bemutatjuk a fenti megközelítés megvalósítását:
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>
Kimenet
Sum of elements from [14] is 50
Idő összetettsége : O(q * log(N)) ahol q a lekérdezések száma.
Kiegészítő tér: ON)