CP: Many range additions

You have an array of n zeros. You will do m operations; each adds a value v to every cell from position l to position r. Print the array when all operations are done.

What to build

Keep a difference array of n + 2 cells. For each operation do diff[l] += v and diff[r + 1] -= v. At the end, print the running sum of diff for positions 1 to n.

Requirements

  • Do each operation in O(1)
  • Use long long
  • Positions are 1-based

Input

The first line has n and m. Each of the next m lines has l r v.

Output

The n final values on one line, separated by spaces.

Constraints

1 ≤ n, m ≤ 100,000. 1 ≤ l ≤ r ≤ n. -10⁹ ≤ v ≤ 10⁹.

Example

Input:

5 3
1 3 2
2 5 -1
4 4 10

Output:

2 1 1 9 -1 

Why it works

Looping over each range costs O(n) per operation, up to 10¹⁰ steps. The difference array costs O(1) per operation and one O(n) pass at the end.

Examples

Example 1 · Input
5 3
1 3 2
2 5 -1
4 4 10
Expected output
2 1 1 9 -1 
Example 2 · Input
3 1
1 3 7
Expected output
7 7 7 

Hints

Hint 1

vector<long long> diff(n + 2, 0);

Hint 2

For each operation: diff[l] += v; diff[r + 1] -= v;

Hint 3

Then cur += diff[i] for i from 1 to n, printing cur each time.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<long long> diff(n + 2, 0);
    for (int i = 0; i < m; i++) {
        int l, r;
        long long v;
        cin >> l >> r >> v;
        diff[l] += v;
        diff[r + 1] -= v;
    }
    long long cur = 0;
    for (int i = 1; i <= n; i++) {
        cur += diff[i];
        cout << cur << " ";
    }
    cout << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Difference arrays →