树状数组类型[一]

PKU-2352 Stars

描述:求每个星星左下方的星星数

坐标先按y从小到大排序,y相等x按从小到大排序。

c[i]表示x=i位置的星星数。

PKU-2481 Cows

描述:每个cow吃草的范围是f=[s,t],如果区间f1严格包含区间f2,则cow1比cow2强。

思路:同pku-2352,cow即是星星,范围即是对应的坐标,不过还需要转化一下,将cows对应到二维坐标上之后,将坐标系逆时针转90°即可。

代码
#include <stdio.h>
#include
<stdlib.h>
#include
<string.h>
#define NL 100002

struct Star {
int x, y;
int id;
}st[NL];
int f[NL], ans[NL];
int n;

int cmp(const void *a, const void *b)
{
struct Star *s1 = (struct Star *)a;
struct Star *s2 = (struct Star *)b;
if (s1->x != s2->x)
return s1->x - s2->x;
return s1->y - s2->y;
}

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

int sum(int k)
{
int cnt = 0;
while (k > 0) {
cnt
+= f[k];
k
-= lowbit(k);
}
return cnt;
}

void update(int k, int c)
{
while (k < NL) {
f[k]
+= c;
k
+= lowbit(k);
}
}

int main()
{
int i, x, y;
while (scanf("%d", &n) != EOF) {
if (!n) break;
for (i=0; i<n; i++) {
scanf(
"%d%d", &x, &y);
st[i].x
= x+1;
st[i].y
= NL-1-y;
st[i].id
= i;
}
qsort(st, n,
sizeof(st[0]), cmp);
memset(f,
0, sizeof(f));
for (i=0; i<n; i++) {
if (i && st[i].x==st[i-1].x && st[i].y==st[i-1].y) {
ans[st[i].id]
= ans[st[i-1].id];
update(st[i].y,
1);
continue;
}
ans[st[i].id]
= sum(st[i].y);
update(st[i].y,
1);
}
for (i=0; i<n; i++) {
if (i) putchar(' ');
printf(
"%d", ans[i]);
}
puts(
"");
}
return 0;
}

 

PKU-3067 Japan

描述:见题。

思路:同上。

posted @ 2010-08-02 14:32  superbin  阅读(423)  评论(0编辑  收藏  举报