codevs 1191 线段树 区间更新(水)

题目描述 Description

在一条数轴上有N个点,分别是1~N。一开始所有的点都被染成黑色。接着
我们进行M次操作,第i次操作将[Li,Ri]这些点染成白色。请输出每个操作执行后
剩余黑色点的个数。

输入描述 Input Description

输入一行为N和M。下面M行每行两个数Li、Ri

输出描述 Output Description

输出M行,为每次操作后剩余黑色点的个数。

样例输入 Sample Input

10 3
3 3
5 7
2 8

样例输出 Sample Output

9
6
3

数据范围及提示 Data Size & Hint

数据限制
对30%的数据有1<=N<=2000,1<=M<=2000
对100%数据有1<=Li<=Ri<=N<=200000,1<=M<=200000

题意:中文题面

题解:区间更新 输出tree[1].sum;

if(tree[root].sum==0) return;//这行代码是关键

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<queue>
 5 #include<stack>
 6 #define ll long long 
 7 #define maxn 200005
 8 using namespace std;
 9 struct node 
10 {
11     int l,r;
12     int sum;
13 }tree[5*maxn];
14 int x,y;
15 int n,q;
16 int ans=0;
17 void buildtree(int root,int left,int right)
18 {
19      tree[root].l=left;
20      tree[root].r=right;
21      if(left==right)
22      {
23       tree[root].sum=1;
24          return ;
25      }
26      int mid=(left+right)>>1;
27      buildtree(root<<1,left,mid);
28      buildtree(root<<1|1,mid+1,right);
29      tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
30 }
31 void updata(int root,int left,int right,int c)
32 {
33     if(tree[root].sum==0) return;
34     if(tree[root].l==left&&tree[root].r==right)
35     {
36         tree[root].sum=0;
37         return ; 
38     }
39     if(tree[root].l==tree[root].r)
40         return ;
41     int mid=(tree[root].l+tree[root].r)>>1;
42     if(right<=mid)
43     updata(root<<1,left,right,c);
44     else
45     {
46         if(left>mid)
47             updata(root<<1|1,left,right,c);
48         else
49         {
50             updata(root<<1,left,mid,c);
51             updata(root<<1|1,mid+1,right,c);
52         }
53     }
54     tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
55 }
56 int main()
57 {
58            scanf("%d %d",&n,&q);
59             buildtree(1,1,n);
60             for(int j=1;j<=q;j++)
61             {
62                 scanf("%d %d",&x,&y);
63                 updata(1,x,y,0);  
64                 printf("%d
",tree[1].sum);}       

return 0;
}
原文地址:https://www.cnblogs.com/hsd-/p/5393697.html