【程序设计思维与实践 Week5 作业B】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 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]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?

输入格式:

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 aa: integer numbers a1,a2,…,an(−106≤ai≤106)
Then qq lines follow, each line represents an operation. The ii-th line contains three integers l,r and c (1≤l≤r≤n,−105≤c≤105) for the ii-th operation.

输出格式:

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

样例:

Input 1:

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

Output 1:

-3 6 9 2

Input 2:

2 1
5 -2
1 2 3

Output 2:

9 2

Input 3:

1 2
0 
1 1 -8
1 1 -6

Output 3:

-14

思路:

暴力解法是对选中的区间里每个数进行加减操作,时间复杂度为O(qn),会超时。
这里采用差分数组的办法,差分数组的第一个数b[1]与原数组a[1]相同,之后每个数b[i]=a[i]-a[i-1],因此原数组等于差分数组前n项和数组;这样对区间l,r的整体加减,可转化为对差分数组两点的操作。如:对区间[l,r]整体加c,等同于对b[l]+c,b[r+1]-c,因为对b[l]+c之后,若之后差分数组不变,表示其差值不变,故相当于l之后的原数组整体加了c,而b[r+1]-c,同理又对r+1之后的原数组整体减c,也就是只改变了[l,r]区间。这样区间的变化便转化为两点的变化,操作完成时候,再求差分数组前n项和数组即可,这样时间复杂度降到O(q+n)。

代码:

#include <iostream>
using namespace std;
const int size=2*1e5+10;
long long a[size],b[size];
int main(int argc, char** argv) {
	int q,n;
	scanf("%d %d",&n,&q);
	a[0]=0;
	for(int i=1;i<=n;i++)
	{
		scanf("%lld",&a[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;
	}
	b[0]=0;
	for(int i=1;i<=n;i++)
	{
		b[i]+=b[i-1];
		printf("%lld ",b[i]);
	}
	printf("\n");
	return 0;
}
发布了24 篇原创文章 · 获赞 8 · 访问量 528

猜你喜欢

转载自blog.csdn.net/weixin_44034698/article/details/104983541