#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <algorithm> #include <stdlib.h> #include <vector> #include <set> #include <math.h> #include <map> using namespace std; typedef long long LL ; const int Max_N = 100008 ; int sum[Max_N<<2] ; /*和*/ int color[Max_N<<2] ;/*颜色,-1表示不是纯色*/ /*向上更新,计算和*/ void push_up(int root){ sum[root] = sum[root<<1] + sum[root<<1|1] ; } /*lazy操作,向下更新时,把纯色的颜色传递下去,同时更新和,若不是纯色则孩子节点的颜色之前已经更新*/ void push_down(int root ,int L ,int R){ if(color[root] != -1){ color[root<<1] = color[root<<1|1] = color[root] ; color[root] = -1 ; /*向下更新就是因为root节点不再纯色*/ int mid = (L+R)>>1 ; sum[root<<1] = (mid-L+1) * color[root<<1] ; sum[root<<1|1] = (R-mid) * color[root<<1|1] ; } } /*建树*/ void make_tree(int L , int R , int root){ color[root] = 1 ; if(L == R){ sum[root] = 1 ; return ; } int mid = (L+R)>>1 ; make_tree(L,mid,root<<1) ; make_tree(mid+1,R,root<<1|1) ; push_up(root) ; } /*更新区间[l,r]颜色为c*/ void update(int l , int r , int c ,int L ,int R ,int root){ if(l <= L && R <= r){ color[root] = c ; sum[root] = (R-L+1) * c ; return ; } push_down(root,L,R) ; int mid = (L+R)>>1 ; if(l <= mid) update(l,r,c,L,mid,root<<1) ; if(r > mid) update(l,r,c,mid+1,R,root<<1|1) ; push_up(root) ; } int main(){ int T ,cas , n ,q , l ,r ,c; scanf("%d",&T) ; for(cas = 1 ; cas <= T ; cas++){ scanf("%d",&n) ; make_tree(1,n,1) ; scanf("%d",&q) ; while(q--){ scanf("%d%d%d",&l,&r,&c) ; update(l,r,c,1,n,1) ; } printf("Case %d: The total value of the hook is %d.\n",cas,sum[1]) ; } return 0 ; }
原文:http://www.cnblogs.com/liyangtianmen/p/3551879.html