Programming thinking week5 assignment B-TT's Magic Cat

topic

One day, the magic cat decided to investigate TT’s ability by giving a problem to him. That is select n cities from the world map, and a[i] represents the asset value owned by the i-th city.
Then the magic cat will perform several operations. Each turn is to choose the city in the interval [l,r] and increase their asset value by c. And finally, it is required to give the asset value of each city after q operations.

Input

The first line contains two integers n,q(1≤n,q≤2⋅105) — the number of cities and operations.
The second line contains elements of the sequence a: integer numbers a1,a2,…,an (−106≤ai≤106).
Then q lines follow, each line represents an operation. The i-th line contains three integers l,r and c (1≤l≤r≤n,−105≤c≤105) for the i-th operation.

Output

Print n integers a1,a2,…,an one per line, and ai should be equal to the final asset value of the i-th city.

Sample Input

4 2
-3 6 8 4
4 4 -2
3 3 1

Sample Output

-3 6 9 2

Ideas

The meaning of the question seems simple, but if you directly modify the points in the interval one by one, the complexity is O (qn), and the timeout.
Since all points in a range are operated, the prefix sum and difference can be used to convert the original array into a difference array and change the interval modification into point modification.
The new array b [i] = a [i] -a [i-1] (i> = 1), then b [] records the difference between two adjacent items in a []. Also a [1] may also be modified, so it willa [0] is assigned as 0As a basis for restoring b [] to a [], it remains unchanged.
Then when modifying the value of the point between the interval [l, r], just modifyb[l],b[r+1], which isDifference between a [l] and a [l-1]as well asDifference between a [r + 1] and a [r].
When b [] is turning a [], a [i] = a [i-1] + b [i].

Code

#include <cstdio>
#include <algorithm>
using namespace std;
long long a[200005],b[200005];//范围q*n最大为2*10^10

int main() {
    int n,q;
    scanf("%d%d",&n,&q);
    for(int i=1;i<=n;i++)//从1开始,留出a[0]=0,a[1]要与a[0]查分,要有一个固定的开始值
        scanf("%lld",&a[i]);
    for(int i=1;i<=n;i++)
        b[i]=a[i]-a[i-1];
    for(int i=0;i<q;i++){
        int l,r,c;
        scanf("%d%d%d",&l,&r,&c);
        b[l]+=c;
        b[r+1]-=c;
    }
    for(int i=1;i<=n;i++)
        a[i]=a[i-1]+b[i];
    for(int i=1;i<=n;i++)
        printf("%lld ",a[i]);
}

to sum up

Pay attention to the data range. Long long should be used. In the future, you need to roughly calculate the data range obtained and use the appropriate type.
Title link

Published 24 original articles · praised 2 · visits 435

Guess you like

Origin blog.csdn.net/weixin_43805228/article/details/105170027