User:Mihai2004marcu

= Difference array (Mars's trick) = In informatics when you need add from position x to position y a number, let's call it z instead of having a complexity of O(x-y+1) for each upload we can do it in O(1) with difference array.

Let 's start with a problem. You have an array of lenght n, and you have to make u uploads from position i to position j you need to add x.

What is the array after the uploads?

'''You need to add x to A[i] and to take x to A[j-1]. As when you are done with the upload you need to have the sum A[i]=A[i]+A[i-1]'''

example

4

2 5 3

6 9 2

1 9 8

4 7 1 So after we uploaded the array we added to each number the one before it after that we obtained

8 11 11 12 12 11 11 10 10 0

Time complexity
We have for each operation O(1) so the complexity is 1*U(operations)=O(U)

And finally when we added the elements we had O(N), so it's O(N+U) so within a second you can perform this algorithm for N=10 000 000 which is quite big

The Code in c++

 * 1) include

using namespace std;

int A[200001],B[200002];

long long N,U,a,b,add;

int main

{

cin>>N;

cin>>U;

for(int i=1; i<=U; ++i)

{

cin>>a>>b>>add;

B[a]+=add;

B[b+1]-=add;

}

for(int i=1; i<=n; ++i)

{

A[i]=A[i-1]+B[i];

cout<<A[i]<<" ";

}

return 0;

}

Algorithm in matrix
We need to add X to all the cells of the matrix from i1, j1 to i2 , j2

So we transform the algorithm into 2d. We add X to A[i1][j1] and A[i2+1][j2+1] and we take X from A[i1][j2+1] and A[i2+1][j1]

The sum is made with :A[i][j]+=A[i-1][j] + A[i][j-1] - A[i-1][j-1]

If we need to add 4 from 2 1 to 4 5