[Programming thinking and practice Week5 job B] TT's Magic Cat

Subject description:

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?

Input formats:

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.

Output formats:

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

Example:

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

Ideas:

Violence solution is selected in each interval the number of addition and subtraction operations, time complexity is O (qn), time out.
Here differential array approach, the number of the first differential array b [1] and the source array a [1] the same, and each number b [i] = a [i ] -a [i-1], so the original n is equal to the difference array, and the array before the array of items; this interval of l, r plus or minus a whole, can be converted to the differential operation of the two arrays. Such as: the interval [l, r] C overall rate, equivalent to b [l] + c, b [r + 1] -c, because After b [l] + c, then if the difference array unchanged, showing the difference is the same, it is equivalent to the original entire array after the addition of l c, and b [r + 1] -c, and empathy for the entire source array minus r + c after 1, which is only changed [ l, r] interval. Such variation interval will change into two points, when the operation is complete, and then determining the difference former and the array can be an array of n items, so that down time complexity O (q + n).

Code:

#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;
}
Published 24 original articles · won praise 8 · views 528

Guess you like

Origin blog.csdn.net/weixin_44034698/article/details/104983541