【区间更新区间求和】HDU 1698 Just a Hook

acm.hdu.edu.cn/showproblem.php?pid=1698

【AC】

 1 #include<cstdio>
 2 const int maxn=100005;
 3 #define lson (i<<1)
 4 #define rson (i<<1|1)
 5 struct Seg
 6 {
 7     int l,r,lazy,val;
 8 }tree[maxn<<2];
 9 int val[maxn];
10 
11 void push_up(int i)
12 {
13     tree[i].val=tree[lson].val+tree[rson].val;
14 }
15 
16 void push_down(int i)
17 {
18     if (tree[i].lazy==-1) return;
19     tree[lson].lazy=tree[i].lazy;
20     tree[rson].lazy=tree[i].lazy;
21     tree[lson].val=tree[i].lazy*(tree[lson].r-tree[lson].l+1);
22     tree[rson].val=tree[i].lazy*(tree[rson].r-tree[rson].l+1);
23     tree[i].lazy=-1;
24 }
25 
26 void build(int l,int r,int i=1)  //build a segment tree of length n, and index 1..n
27 {
28     tree[i].l=l;
29     tree[i].r=r;
30     tree[i].lazy=-1;
31     if (l==r) tree[i].val=val[l];
32     else
33     {
34         int mid=l+r>>1;
35         build(l,mid,lson);
36         build(mid+1,r,rson);
37         push_up(i);
38     }
39 }
40 
41 void setval(int l,int r,int x,int i=1)
42 {
43     if (tree[i].l==l && tree[i].r==r)
44     {
45         tree[i].lazy=x;
46         tree[i].val=x*(r-l+1);
47     }
48     else
49     {
50         push_down(i);
51         int mid=tree[i].l+tree[i].r>>1;
52         if (r<=mid) setval(l,r,x,lson);
53         else if (l>mid) setval(l,r,x,rson);
54         else
55         {
56             setval(l,mid,x,lson);
57             setval(mid+1,r,x,rson);
58         }
59         push_up(i);
60     }
61 }
62 
63 int query(int l,int r,int i=1)
64 {
65     if (tree[i].l==l && r==tree[i].r) return tree[i].val;
66     push_down(i);
67     int mid=tree[i].l+tree[i].r>>1;
68     if (r<=mid) return query(l,r,lson);
69     if (l>mid) return query(l,r,rson);
70     return query(l,mid,lson)+query(mid+1,r,rson);
71 }
72 
73 int main()
74 {
75     int t;
76     scanf("%d",&t);
77     int cas=0;
78     while (t--)
79     {
80         int n;
81         scanf("%d",&n);
82         for (int i=1;i<=n;i++) val[i]=1;
83         build(1,n);
84         int m;
85         scanf("%d",&m);
86         for (int i=0;i<m;i++)
87         {
88             int l,r,k;
89             scanf("%d%d%d",&l,&r,&k);
90             setval(l,r,k);
91         }
92         printf("Case %d: The total value of the hook is %d.\n",++cas,query(1,n));
93     }
94     return 0;
95 }
View Code

 

posted @ 2017-08-22 18:58  shulin15  阅读(159)  评论(0编辑  收藏  举报