思路:线段树成段更新
分析:
1 简单的线段树的成段更新,我们把它看成区间的更改和区间的求和即可,那这样我们只要建立好线段树然后每一次进行更新,最后对每一个[i , i]区间进行求和即可
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 100010;
struct Node{
int left;
int right;
int mark;//延时标记
int sum;
};
Node node[4*MAXN];
int N;
//向上更新
void push_up(int pos){
node[pos].sum = node[pos<<1].sum + node[(pos<<1)+1].sum;
}
//向下更新i
void push_down(int pos){
if(node[pos].mark){
node[pos<<1].mark += node[pos].mark;
node[(pos<<1)+1].mark += node[pos].mark;
node[pos<<1].sum += node[pos].mark*(node[pos<<1].right-node[pos<<1].left+1);
node[(pos<<1)+1].sum += node[pos].mark*(node[(pos<<1)+1].right-node[(pos<<1)+1].left+1);
node[pos].mark = 0;
}
}
//建立线段树
void buildTree(int left , int right , int pos){
node[pos].left = left;
node[pos].right = right;
node[pos].mark = 0;
if(left == right){
node[pos].sum = 0;
return;
}
int mid = (left+right)>>1;
buildTree(left , mid , pos<<1);
buildTree(mid+1 , right , (pos<<1)+1);
push_up(pos);
}
//更新
void update(int left , int right , int value , int pos){
if(left <= node[pos].left && right >= node[pos].right){
node[pos].mark += value;
node[pos].sum += value*(node[pos].right-node[pos].left+1);
return;
}
push_down(pos);
int mid = (node[pos].left + node[pos].right)>>1;
if(right <= mid)
update(left , right , value , pos<<1);
else if(left > mid)
update(left , right , value , (pos<<1)+1);
else{
update(left , mid , value , pos<<1);
update(mid+1 , right , value , (pos<<1)+1);
}
push_up(pos);
}
//查询
int query(int left , int right , int pos){
if(node[pos].left == left && node[pos].right == right)
return node[pos].sum;
int mid = (node[pos].left+node[pos].right)>>1;
push_down(pos);//继续向下更新,这样才能完全更新完毕
if(right <= mid)
return query(left , right , pos<<1);
else if(left > mid)
return query(left , right , (pos<<1)+1);
else
return query(left , mid , pos<<1) + query(mid+1 , right , (pos<<1)+1);
}
int main(){
int x , y;
while(scanf("%d" , &N) && N){
buildTree(1 , N , 1);
int cnt = N;
while(cnt--){
scanf("%d%d" , &x , &y);
update(x , y , 1 , 1);
}
for(int i = 1 ; i <= N ; i++){
if(i == 1) printf("%d" , query(i , i , 1));
else printf(" %d" , query(i , i , 1));
}
printf("\n");
}
return 0;
}