现在的位置: 首页 > 综合 > 正文

树状数组的例题-校门外的树

2012年08月07日 ⁄ 综合 ⁄ 共 1014字 ⁄ 字号 评论关闭

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

输入格式 Input Format
第一行n,m表示道路总长为n,共有m个操作
接下来m行为m个操作

输出格式 Output Format
对于每个k=2输出一个答案

样例输入 Sample Input
5 4 1 1 3 2 2 5 1 2 4 2 3 5

样例输出 Sample Output
1 2

注释 Hint
范围:
20%的数据保证,n,m<=100
60%的数据保证,n <=1000,m<=50000
100%的数据保证,n,m<=50000

【参考程序】://树状数组
#include<cstring>
#include<cstdio>
#include<iostream>
using namespace
std;

typedef int array[50010];
array
a,b;
int
n,m;
int lowbit(int
x)
{

    return x^(x&(x-1
));
}

void add(int x,array &c
)
{

    while (x<=
n)
    {

        c[x]++
;
        x
+=lowbit
(x);
    }

}
int getsum(int
x,array c)
{

    int sum=0
;
   
while
(x)
    {

        sum+=c[x];
        x-=lowbit
(x);
    }

    return
sum;
}

int
main()
{

    scanf("%d%d",&n,&m
);
    memset(a
,0,sizeof
(a));
    memset(b,
0,sizeof
(b));
   
int
t,l,r;
   
for (int i=1;i<=m;i++
)
    {

        scanf("%d%d%d",&t,&l,&r
);
       
if (t==1
)
        {

            add(l,a); add(r,b);
        }

        else
        {
            int s=getsum(r,a)-getsum(l-1,
b);
            printf(
"%d/n",
s);
        }

    }
    return 0
;
}

抱歉!评论已关闭.