HDU1541 Stars 树状数组

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

题义为给定N个点按照先x轴,后y轴坐标排序,求某一点的左下角的星星数量,刚开始用二维的树状数组来做,结果肯定是内存不过用。

该题正解为在给定的坐标点的排序后,只对x轴坐标建立一个一维数组,对于当前状态按x轴将平面划分成M个区域,由于给定的点的y轴坐标一定是当前最高的,所以直接对横坐标前求和即可。

代码如下:

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <map>
#define MAXN 32005
using namespace std;

int N, res[MAXN+5], c[MAXN+5];

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

inline void modify(int pos, int val)
{
for (int i = pos; i <= MAXN; i += lowbit(i))
c[i] += val;
}

inline int getsum(int pos)
{
int s = 0;
for (int i = pos; i > 0; i -= lowbit(i))
{
s += c[i];
}
return s;
}

int main()
{
int x, y;
while (scanf("%d", &N) == 1)
{
memset(c, 0, sizeof (c));
memset(res, 0, sizeof (res));
for (int i = 0; i < N; ++i)
{
scanf("%d %d", &x, &y);
x++;
res[getsum(x)]++;
modify(x, 1);
}
for (int i = 0; i < N; ++i)
printf("%d\n", res[i]);
}
return 0;
}



原文地址:https://www.cnblogs.com/Lyush/p/2368453.html