HDOJ 1541 star(树状数组)

来源:互联网 发布:碳基生物知乎 编辑:程序博客网 时间:2024/05/19 04:03


http://acm.hdu.edu.cn/showproblem.php?pid=1541


这道题告诉我们若干颗星星的坐标,告诉我们的时候y坐标已经按照升序排列了。对于每一颗星,它的等级数等于它左边和左上角星星的颗数。最后问每一颗星星的等级。

把星星按照给我们的顺序(就是y坐标从小到大的顺序),依次把一个数组中下标为x的元素加1。对于某一颗星,坐标为x,那么把数组中下标为x及之前的所有元素相加,就是求了这颗星左边及左上角的星星数,然后再把下标为x的元素加1。(这颗星星本身不能算进去)


#include<cstdio>#include<cstring>#include<cstdio>#include<algorithm>#define N 32005using namespace std;int n, c[N], level[N];int lowbit(int x){    return x & (-x);}int query(int x){    int sum = 0;    while (x > 0)    {        sum += c[x];        x -= lowbit(x);    }    return sum;}int add(int i, int d){    while (i <= 32001)    {        c[i] += d;        i += lowbit(i);    }}int main(){    int ans, x, y;    while (~scanf("%d", &n))    {        memset(c, 0, sizeof(c));        memset(level, 0, sizeof(level));        for (int i = 1; i <= n; i++)        {            scanf("%d%d", &x, &y);            x++;            ans = query(x);            level[ans]++;            add(x, 1);        }        for (int i = 0; i < n; i++)            printf("%d\n", level[i]);    }    return 0;}

0 0
原创粉丝点击