@@ -3,7 +3,7 @@ id: more-prefix-sums
3
3
redirects :
4
4
- /silver/prefix-sums-2
5
5
title : ' More on Prefix Sums'
6
- author : Darren Yao, Neo Wang, Qi Wang
6
+ author : Darren Yao, Neo Wang, Qi Wang, Mihnea Brebenel
7
7
contributors : Jesse Choe, Kevin Sheng, Brad Ma, Juheon Rhee
8
8
description :
9
9
' Max subarray sum, prefix sums in two dimensions, and a more complicated
@@ -652,6 +652,85 @@ for _ in range(query_num):
652
652
653
653
<Problems problems = " cum2" hideSuggestProblemButton />
654
654
655
+ ## Difference Arrays
656
+
657
+ <Resources >
658
+ <Resource source = " Codeforces" title = " An Introduction To Difference Arrays" url = " https://codeforces.com/blog/entry/78762" />
659
+ </Resources >
660
+
661
+ <FocusProblem problem = " sample3" />
662
+
663
+ ### Explanation - Greg and Array
664
+
665
+ Let's create an array $s$, where $s[i ]$ is the number of times operation $i$ is applied.
666
+ The important step is how we update it.
667
+
668
+ For an interval $[l , r ]$, we can't loop through the interval and
669
+ increment each value, as that would be $\mathcal{O}(MK)$ and too slow.
670
+ Instead, we increment $s[l ]$ by one and decrement $s[r + 1 ]$ by one.
671
+
672
+ Now, we get the *actual* array by computing its prefix sum array,
673
+ resulting in $\mathcal{O}(M)$ time complexity.
674
+ The second part, applying the operations, can be done exactly the same way.
675
+
676
+ ### Implementation - Greg and Array
677
+
678
+ **Time Complexity:** $ \mathcal {O }(N + M )$
679
+
680
+ <LanguageSection >
681
+ <CPPSection >
682
+
683
+ ```cpp
684
+ #include <array >
685
+ #include <iostream >
686
+ #include <vector >
687
+
688
+ using namespace std;
689
+
690
+ int main() {
691
+ int n , m , k ;
692
+ cin >> n >> m >> k ;
693
+ vector < int > a (n + 1 );
694
+ for (int i = 1 ; i <= n ; i ++ ) { cin >> a[i ]; }
695
+ vector<array<int, 3>> updates(m);
696
+ for (array<int, 3> &update : updates ) {
697
+ cin >> update[0 ] >> update[1 ] >> update[2 ];
698
+ }
699
+
700
+ vector<long long> s(m + 2);
701
+ vector<long long> add(n + 2, 0);
702
+ for (int i = 0; i < k; i++) {
703
+ int x, y;
704
+ cin >> x >> y;
705
+ s[x ]++;
706
+ s[y + 1 ]--;
707
+ }
708
+
709
+ for (int i = 1; i <= m; i++) {
710
+ // Apply prefix sums
711
+ s[i ] += s[i - 1 ];
712
+
713
+ // At the same time compute the second difference array
714
+ add[updates [i - 1 ][0 ]] += s[i ] * updates[i - 1 ][2 ];
715
+ add[updates [i - 1 ][1 ] + 1 ] -= s[i ] * updates[i - 1 ][2 ];
716
+ }
717
+
718
+ for (int i = 1; i <= n; i++) {
719
+ // Apply prefix sums
720
+ add[i ] += add[i - 1 ];
721
+ cout << a[i ] + add[i ] << ' ' ;
722
+ }
723
+ cout << endl ;
724
+ }
725
+ ` ` `
726
+
727
+ </CPPSection>
728
+ </LanguageSection>
729
+
730
+ ### Problems
731
+
732
+ <Problems problems="difference-arrays-problemset" />
733
+
655
734
## Quiz
656
735
657
736
<Quiz>
0 commit comments