---
title: "[树状数组]HOJ 10069 星星的等级"
author: "Coco_young"
date: "2012-06-23T23:39:00Z"
tags: []
slug: "hoj-10069"
draft: false
lastmod: "2013-02-03T02:37:20Z"
id: 1786445
url: "https://coco-young.iteye.com/blog/1786445"
---

传送门：[http://acm.hnu.cn/online/?action=problem&type=show&id=10069&courseid=0](http://acm.hnu.cn/online/?action=problem&type=show&id=10069&courseid=0)

题目描述：给定若干个二维平面上 的点，如果a.x&lt;=b.x&&a.y&gt;=b.y则说a的等级比b高(如果a==b，则他们等级相同)，要求对于每个点，输出比他等级高的点的总数。

解题思路：把星星按照y的递减序和x的递增序排序，然后对x轴建立树状数组，依次将每个星星插入树状数组（在插入前统计出1-当前坐标和区间和，记录下来），然后再把相同的星星的记录下来的数据换成他们之中第一个被插入树状数组的星星的值，即可，注意，需要离散化（即前面说的树状数组是在离散化后的x轴下建立起来的）

各种蛋疼：

1.如果比较函数不加最后的那句idx&lt;s.idx那么就WA（应该这样写会导致排序的结果出现问题）

2.开始没看到(如果a==b，则他们等级相同)..

第一个问题比较蛋疼，以后需要注意！

代码：

```
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 111111;
struct Star{
    int x,y,idx;
    bool operator < (const Star &s) const{
        if(y!=s.y){
            return y>s.y;
        }else if(x!=s.x){
            return x<s.x;
        }else{
            return idx<s.idx;
        }//这。。。。。
    }
    bool operator == (const Star &s) const{
        return x==s.x&&y==s.y;
    }
}stars[MAXN];
int arr[MAXN],c[MAXN],res[MAXN],N,M;
int bs(int x){
    int l = 0, r = M-1,m;
    while(l<=r){
        m = (l+r)>>1;
        if(arr[m]==x)return m;
        else if(x<arr[m])r = m-1;
        else l = m+1;
    }
    return -1;
}
int lowbit(int x){
    return x&(-x);
}
int sum(int pos){
    int s = 0;
    while(pos>0){
        s+=c[pos];
        pos-=lowbit(pos);
    }
    return s;
}
void add(int pos){
    while(pos<=M){
        c[pos]++;
        pos+=lowbit(pos);
    }
}
int main(){
    while(scanf("%d",&N)!=EOF){
        memset(c,0,sizeof(c));
        M = 0;
        for(int i=0;i<N;i++){
            scanf("%d%d",&stars[i].x,&stars[i].y);
            stars[i].idx = i;
            arr[M++] = stars[i].x;
        }
        sort(arr,arr+M);
        int temp = 1;
        for(int i=1;i<M;i++)if(arr[i]!=arr[i-1])arr[temp++] = arr[i];
        M = temp;
        sort(stars,stars+N);
        for(int i=0;i<N;i++){
            int pos = bs(stars[i].x)+1;
            res[stars[i].idx] = sum(pos);
            add(pos);
        }
        for(int i=1;i<N;i++){
            if(stars[i]==stars[i-1])res[i]=res[i-1];
        }
        for(int i=0;i<N;i++){
            if(i) printf(" %d",res[i]);
            else printf("%d",res[i]);
        }
        printf("\n");
    }
    return 0;
}
```