• + 3 comments

    These two places helped me to understand this algorithm more clearly. Prefix_sum_array_and_difference_array Stack Overflow

    If you want a simple and direct explanation: Initial, the array is 0 0 0 0 0

    after the first operation, 1 2 100
    it will become
    seq1: 100 100 0 0 0
    and after second 2 5 100
    seq2: 0 100 100 100 100
    and after 3 4 100
    seq2: 0 0 100 100 0
    

    but when we apply difference array at every step, we will get

    diff seq of seq1: 100 0 -100 0 0
    diff seq of seq2: 0 100 0 0 0 -100
    diff seq of seq3: 0 0 100 0 -100
    

    One important property is the difference sequence of the sum of the sequences is the sum of the difference sequences.

    it will give us,

    100 100 0 0 -100 -100(for clarity purpose only)
    

    or you can add all the sequences as

    seq1+seq2+seq3 = 100 200 200 200 100
    

    and then find the difference seq or the difference array which is 100 100 0 0 -100 and then find the prefix array.

    Why we ignore the first 100??? Read the first article about difference array and prefix sum array!!!!

    and after this, do prefix sum

    100 200 200 200 100 0
    

    Ignore last 0 as the last index we considered is for clarity purpose only.

    so,both these steps find the difference array for us:)

    a[p]+=sum;
    if((q+1)<=N) a[q+1]-=sum;