一本通1536 数星星 Stars

· · 个人记录

一本通1536 数星星 Stars

这题一看,是道二维偏序的题目,它一般用树状数组来维护。

原题链接

http://ybt.ssoier.cn:8088/problem_show.php?pid=1536

树状数组

众所周知,每个数都可以拆分成2的幂的和的形式,如:

\begin{aligned} &7=2^2+2^1+2^0\\ &13=2^3+2^2+2^0\\ &123=2^6+2^5+2^4+2^3+2^1+2^0 \end{aligned}

树状数组(\texttt{Binary Indexed Tree}),简称\texttt{BIT}。主要用来求前缀和。

1.能够进行区间修改。

2.时间复杂度很优秀:O(\operatorname{log \space N}).

\begin{aligned} a[\space]\space :\space &5\space\space\space 2\space\space\space 1\space\space\space 3\space\space\space 4\space\space\space 3\space\space\space 1\\ \text{下标}\space :\space &1\space\space\space 2\space\space\space 3\space\space\space 4\space\space\space 5\space\space\space 6\space\space\space 7 \end{aligned} 7=4+2+1=2^2+2^1+2^0 \text{那么可以拆分成:}b[16]+b[18]+b[19]

获取x在二进制形式下最右边的1及之后的0构成的数。

如:

\begin{aligned} &(10100)_{2}\to(100)_{2}\to(4)_{10} \\ &(10011)_{2}\to(1)_{2}\to(1)_{10} \end{aligned}

如何获取整数x的\operatorname{lowbit}呢?x&(-x)

&的规则:有2个1就是1,有0就是0。

原码,反码,补码:

\begin{aligned} &\text{原码:}01001\\ &\text{反码:}10110\space\space\space\space\space \text{与原码相对}\\ &\text{补码:}10111\space\space\space\space\space\text{反码+1} \end{aligned} x\to-x -x\text{是}x\text{的补码}

所以x的\operatorname{lowbit}为x&-x。

#include<cstdio>
using namespace std;
const int N = 5 * 1e5 + 5;

int n, m;
int x, y;
int num[N], sum[N];

int lowbit (int x) {//定义lowbit函数
    return x & (-x);
}

void update (int x, int y) {
    while (x <= n) {//从x遍历
        sum[x] += y;
        x += lowbit(x);
    }
    return ;
}

int query (int x) {
    int res = 0;
    while (x != 0) {//遍历
        res += sum[x];
        x -= lowbit(x);
    }
    return res;
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &num[i]);
        update(i, num[i]);
    }
    for (int i = 1; i <= m; ++i) {
        int opt, x, y;
        scanf("%d%d%d", &opt, &x, &y);
        if (opt == 1) {
            update(x, y);
        }
        else {
            printf("%d\n", query(y) - query(x - 1));
        }
    }
    return 0;
}

本题题解

这题是道二维偏序的模板题,由于y轴是按顺序给你的,所以只需要求x的偏序了。

当x=0时,lowbit(x)始终为零,不会改变,会进入死循环,由于x可能为0,我们统一将x+1。

定义ans数组,表示要输出的答案,和stars数组,stars[i]表示i的星星数。

代码:

#include<cstdio>
using namespace std;

int n;
int ans[32005];
int stars[32005];

int lowbit (int x) {
    return x & (-x);
}

void update (int x, int y) {//修改星星数的函数
    while (x <= 32005) {
        stars[x] += y;
        x += lowbit(x);
    }
    return ;
}

int query (int x) {//查询星星数的函数
    int res = 0;
    while (x != 0) {
        res += stars[x];
        x -= lowbit(x);
    }
    return res;
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        int x, y;
        scanf("%d%d", &x, &y);
        ++x;
        ++ans[query(x)];//统计答案
        update(x, 1);//x处有自己,所以要加1
    }
    for (int i = 0; i < n; ++i) {//输出
        printf("%d\n", ans[i]);
    }
    return 0;
}

码字不易,能否给个赞再走?