题目
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 nn cities from the world map, and a[i]a[i] represents the asset value owned by the ii-th city.Then the magic cat will perform several operations. Each turn is to choose the city in the interval [l,r][l,r] and increase their asset value by cc. And finally, it is required to give the asset value of each city after qq operations.Could you help TT find the answer?
Input
The first line contains two integers n,qn,q (1≤n,q≤2⋅105)(1≤n,q≤2·105) — the number of cities and operations.The second line contains elements of the sequence aa: integer numbers a1,a2,…,ana1,a2,…,an (−106≤ai≤106)(−106≤ai≤106).Then qq lines follow, each line represents an operation. The ii-th line contains three integers l,rl,r and cc (1≤l≤r≤n,−105≤c≤105)(1≤l≤r≤n,−105≤c≤105) for the ii-th operation.
Output
Print nn integers a1,a2,…,ana1,a2,…,an one per line, and aiai should be equal to the final asset value of the ii-th city.
Example
Input
4 2
-3 6 8 4
4 4 -2
3 3 1
Output
-3 6 9 2
题目解析
其实就是给一组数,每次选一部分连续的数加上某个数,可以使用差分的方法,将对一组数的操作转化为对两个数的操作,最后用逐步累加即可。
完整代码
#include<iostream>
using namespace std;
int n, q;
const int maxn = 1e6 + 10;
int a[maxn] = { 0 };
long long minu[maxn] = { 0 };//精度问题,数据范围判断失误
int l, r, c;
int main()
{
cin >> n >> q;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= n; i++)
minu[i] = (long long)a[i] - a[i - 1];//让后一个数减前一个数
for (int i = 1; i <= q; i++)
{//将对[l,r]操作转化为对l,r+1的操作
cin >> l >> r >> c;
minu[l] += c;
minu[r + 1] -= c;
}
for (int i = 1; i < n; i++)
{//累加出结果
minu[i] += minu[i - 1];
cout << minu[i] << ' ';
}
minu[n] += minu[n - 1];
cout << minu[n] << endl;
return 0;
}
总结
差分的作用就是通过差的形式将对一组数的加减转化为对两个数的加减,降低复杂度。
注意事项
long long 防止爆精度