—— by A Code Rabbit
Description
在直角坐标系上有几个星星。
星星的等级等于在它左下方的星星的数量(含左方和下方)。
计算各等级的星星数。
Type
Advanced Data Structures :: Segment Tree
Advanced Data Structures :: Binary Indexed Tree
Analysis
由于题目的输入,是排序好的。
就不需要我们排序了。
否则我们要做的第一步,就是按 y 排序。
因此输入中的 y 是没有用的。
一颗星星的等级就等于在它之前,x坐标小于等于它的星星有几个。
用树状数组数组记录下 x 坐标的星星数,即可轻松解决。
要注意,数据范围 0 <= x <= 32000。
而树状数组不能有 0 下标,因此需要将所有 x 坐标 + 1。
且需要开大小为 32001 的数状数组。
Solution
// POJ 2352
// Stars
// by A Code Rabbit
#include <cstdio>
#include <cstring>
const int MAXN = 32002;
struct Bit {
int c[MAXN], n;
void Init(int x) { memset(c, 0, sizeof(c)); n = x; }
void Add(int x, int y) {
while (x <= n) { c[x] += y; x += x & -x; }
}
int Sum(int x) {
int res = 0;
while (x > 0) { res += c[x]; x -= x & -x; }
return res;
}
};
int n;
int x, y;
Bit bit;
int cnt[15002];
int main() {
while (scanf("%d", &n) != EOF) {
memset(cnt, 0, sizeof(cnt));
bit.Init(32001);
for (int i = 0; i < n; i++) {
scanf("%d%d", &x, &y);
cnt[bit.Sum(x + 1)]++;
bit.Add(x + 1, 1);
}
for (int i = 0; i < n; i++) {
printf("%d\n", cnt[i]);
}
}
return 0;
}
本文介绍如何利用树状数组解决排序输入条件下的问题,具体应用在计算直角坐标系中星星的等级数量。
437

被折叠的 条评论
为什么被折叠?



