20,200,314 divided apples (prefix and differential)

Title Description
children in a row, the teacher gave them apples points.
Children from left to right numeral 1 ... N. M has a teacher, each of the i-th teacher give Li th to th Ri, a total of Ri-Li + 1 children each made Ci apples.
Finally the teacher wanted to know how many children each apple.

And the data size agreed
100% data, N, M≤100000,1≤Li≤Ri≤N, 0≤Ci≤100.

Input
of the first row two integers N, M, represents the number of children and a number of teachers.
Next M rows, each row of three integers Li, Ri, Ci, meaning the subject as expression.
Output
number of line N, the i-th denotes the i-th hand children fruit.
Sample input
. 5. 3
. 1. 1 2
2 2. 3
2. 5. 3
Sample Output
16533

Well, first fill knowledge of it
if you do not prefix and the violence of the time complexity is M * (Ri-Li + 1 ), namely M N, you can write, write out very smooth discovery TLE.
(Heart os:! I really want to Tucao this TLE, the whole idea of the method is wrong, that is not the result of an error, is not thought to find an easy way to re-think this really makes people scratching their heads)
so prefix and complexity M
(O (1)) = O (M)
D [i] - 1 and i represents the array elements, element interval for lr sum d = d [r] -d [ l-1], to obtain the and in the interval the elements.
And two-dimensional prefix
In O (1) time complexity is determined and the matrix elements (x1, y1) (x2, y2) is determined by d (x2, y2) -d (x1, y1-1) diagonal points -d (x1-1, y1) -d (x1-1, y1-1)
but! We clearly see the points it requires Apple Apple is the number of intervals in the hands of every child! OK by difference
the difference the array d [i] = a [i ] -a [i-1], so that a [i] = d [1 ] + d [2] + ... + d [i]! We want to calculate the value of a d with an array of arrays. Can imagine, in [l, r] plus or minus a numeric interval, only d [l] and the value of d [r + 1] has changed. and so! ! ! I only change every d [l] and d [r + 1] can be! d [l] + = k, d [r + 1] - = k, the final output obtained by the above formula a [i] to

Closer to home divided the code Apple
finished school seniors to see the code is very clear to read the
beginning of the hands of children so Apple did not have a 0 array can not write
the global array is equivalent to the value 0., partly random value, there are other variations assignment 0
in addition seniors this format control write too good, right! Really very beautiful!

#include <bits/stdc++.h>
using namespace std;
const int n=1e5+10; 
int d[n];
int main(){
	int N,M;
	cin>>N>>M;
	while(M--){
		int l,r,c;
		cin>>l>>r>>c;
		d[l]+=c;
		d[r+1]-=c;
	}
	int sum=0; 
	for(int i=1;i<=N;i++){
		sum+=d[i];
		printf("%d%c",sum,i==n?'\n':' ');
	}
	return 0;
} 
Published 37 original articles · won praise 0 · Views 364

Guess you like

Origin blog.csdn.net/weixin_45351699/article/details/104932364