线段树/树状数组问题 | 问题集合

写在前面

 

线段树代码实在冗长,于是乎能用树状数组直接搞的就懒得打线段树了(:溜

 


 

 1.P2620[QZYZ] 校门外的树

描述 Description

校门外有很多树,有苹果树,香蕉树,有会扔石头的,有可以吃掉补充体力的……
如今学校决定在某个时刻在某一段种上一种树,保证任一时刻不会出现两段相同种类的树,现有两个操作:
K=1,读入l,r表示在l~r之间种上的一种树
K=2,读入l,r表示询问l~r之间能见到多少种树
(l,r>0)

输入格式 InputFormat

第一行n,m表示道路总长为n,共有m个操作
接下来m行为m个操作

输出格式 OutputFormat

对于每个k=2输出一个答案

样例输入 SampleInput

4

3
5
4
5

样例输出 SampleOutput

1 

2 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #define lowbit(x) x&(-x)
 6 
 7 using namespace std;
 8 
 9 int l[1001] , r[1001] , n , m;
10  
11 int read()
12 {
13     int x = 0;
14     char c = getchar();
15     while(c < '0' || c > '9') c = getchar();
16     while(c >= '0' && c <= '9') x = x*10 + c-'0' , c = getchar();
17     return x;
18 }
19 
20 void add(int arr[],int x)
21 {
22     while (x<=n)
23     {
24         arr[x]++;
25         x+=lowbit(x);
26     }
27     return;
28 }
29  
30 int query(int arr[],int x)
31 {
32     int ans=0;
33     while (x>0)
34     {
35         ans+=arr[x];
36         x-=lowbit(x);
37     }
38     return ans;
39 }
40 
41 int main()
42 {
43     cin >> n >> m;
44     while(m--){
45         int x , y , z;
46         z = read(),x = read(),y = read();
47         if (z == 1)
48             add(l , x),add(r , y);
49         else cout << query(l , y) - query(r , x-1) << endl;
50     } 
51     return 0;
52 }
校门外的树

 

posted @ 2017-08-14 13:35  Yuns's  阅读(185)  评论(0编辑  收藏  举报