树状数组 例题

博客讨论了如何利用树状数组解决多种区间计数问题,包括气球涂色次数、星星等级计算、道路交叉点数目以及计算一头牛比其他牛强壮的数量。文章通过举例和代码解释了树状数组在这些问题中的应用,并提供了相关的AC代码和解题思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 具体模板详见  https://blog.youkuaiyun.com/zcy19990813/article/details/81297476

Color the ball

N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?

Input

每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。
当N = 0,输入结束。

Output

每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。

Sample Input

3
1 1
2 2
3 3
3
1 1
1 2
1 3
0

Sample Output

1 1 1
3 2 1

 AC代码:

#include<iostream>
#include <algorithm>
#include <cstdlib>
#include<cstdio>
#include<cstring>
#include <cmath>
using namespace std;
const int M=200000+10;
const int MAX=0x3f3f3f3f;
typedef long long ll;
ll a[101010],c[101010],t[101010],n;
ll lowbit(ll x)
{
    return x&(-x);
}
ll Getsum(ll i)
{
    ll ans=0;
    while(i>0)
    {
        ans+=c[i];
        i-=lowbit(i);
    }
    return ans;
}
void update(ll i,ll v)
{
    while(i<=n)
    {
        c[i]+=v;
        i+=lowbit(i);
    }
}
int main()
{
    ll m,i,j,aa,bb;
    while(~scanf("%lld",&n)&&n)
    {
        memset(a,0,sizeof(a));
        memset(c,0,sizeof(c));
        for(i=1;i<=n;i++)
        {
            scanf("%lld%lld",&aa,&bb);
            update(aa,1);
            update(bb+1,-1);
        }
        for(i=1;i<n;i++)
          printf("%lld ",Getsum(i));
        printf("%lld\n",Getsum(n));
    }
    return 0;
}

Astronomers often examine star maps where stars are represented by points on a plane and each star has Cartesian coordinates. Let the level of a star be an amount of the stars that are not higher and not to the right of the given star. Astronomers want to know the distribution of the levels of the stars.

 


For example, look at the map shown on the figure above. Level of the star number 5 is equal to 3 (it's formed by three stars with a numbers 1, 2 and 4). And the levels of the stars numbered by 2 and 4 are 1. At this map there are only one star of the level 0, two stars of the level 1, one star of the

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值