week5 作业B TT's Magic Cat

TT’s Magic Cat

Thanks to everyone’s help last week, TT finally got a cute cat. But what TT didn’t expect is that this is a magic cat. 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.Could you help TT find the answer?

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.

Examples

Input:
4 2
-3 6 8 4
4 4 -2
3 3 1
Output:
-3 6 9 2

Input:
2 1
5 -2
1 2 4
Output:
9 2

Input:
1 2
0
1 1 -8
1 1 -6
Output:
-14

我的思路:
这道题需要使用到前缀和差分,如果直接对区间内的数逐个进行加减,则所需的时间复杂度是十分巨大的。那么,我们可以利用差分的方法,来解决这一问题。通过计算原数组a内的相邻数之间的差,得到一个差分数组b(即b[0]=a[0],b[i]=a[i]-a[i-1])。这个时候,如果我们需要对于区间[k,m]内的数,整体进行加num操作,只需要b[k]+num,b[m+1]-num即可。为了更快地得到原数组在计算之后的值(a[i]=b[0]+b[1]+…+b[i]),需要对于数组B进行前缀处理。即计算一个sum数组(sum[i]=sum[i-1]+b[i]),这样综合两种方法,最终的计算后数组内的元素变为a[i]=sum[i-1]+b[i]。

我的总结:
前缀和差分,是对于一个区间内的数进行加减时的一个很好的优化方法,可以达到降低时间复杂度的目的。
我的代码:

#include<cstdio>
using namespace std;

long long a[200001],b[200001],sum[200001],n,q,m,w,t;

void ini()
{
    b[1]=a[1];
    for(long long i=2;i<=n;i++)
    {
        b[i]=a[i]-a[i-1];
    }
}

void inii()
{
    sum[1]=b[1];
    for(long long i=2;i<=n;i++)
    {
        sum[i]=sum[i-1]+b[i];
    }
}

long long add(long long ind)
{
    long long ans=0;
    for(long long i=1;i<=ind;i++) ans+=b[i];
    return ans;
}

int main()
{
    scanf("%lld%lld",&n,&q);
    for (long long i=1;i<=n;i++) scanf("%lld",&a[i]);
    ini();
    for(long long i=0;i<q;i++)
    {
        scanf("%lld%lld%lld",&m,&w,&t);
        b[m]+=t;
        b[w+1]-=t;
    }
    inii();
    for(long long i=1;i<=n;i++) printf("%lld ",sum[i-1]+b[i]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值