现在的位置: 首页 > 综合 > 正文

hdu 1541 Stars(树状数组)

2012年02月22日 ⁄ 综合 ⁄ 共 2117字 ⁄ 字号 评论关闭

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

开始知道是用树状数组做,但想了好半天不知道怎么用,总觉得要先排序才能做。但是排序的话复杂度就上去了啊。

纠结了半天才读到那句 Stars are listed in ascending order of Y coordinate.擦了个擦的,早看见不完了。

c[pos]表示1到pos的和,也就是当前星星前有几个(包含当前)。用cnt记录各等级数量。

code:

#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <set>
#include <queue>
#include <stack>
#include <fstream>
#include <iomanip>
#include <bitset>
#include <list>
#include <ctime>
using namespace std ;

#define SET(arr, what)  memset(arr, what, sizeof(arr))
#define FF(i, a)        for(i=0; i<a; i++)
#define SD(a)           scanf("%d", &a)
#define SSD(a, b)       scanf("%d%d", &a, &b)
#define SF(a)           scanf("%lf", &a)
#define SS(a)           scanf("%s", a)
#define SLD(a)          scanf("%lld", &a)
#define PF(a)           printf("%d\n", a)
#define PPF(a, b)       printf("%d %d\n", a, b)
#define SZ(arr)         (int)a.size()
#define SWAP(a,b)       a=a xor b;b= a xor b;a=a xor b;
#define read            freopen("in.txt", "r", stdin)
#define write            freopen("out.txt", "w", stdout)
#define MAX             1<<30
#define ESP             1e-5
#define lson            l, m, rt<<1
#define rson            m+1, r, rt<<1|1
template<class T> inline T sqr(T a){return a*a;}
template<class T> inline void AMin(T &a,T b){if(a==-1||a>b)a=b;}
template<class T> inline void AMax(T &a,T b){if(a<b)a=b;}
template<class T> inline T Min(T a,T b){return a>b?b:a;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
const int maxn = 32000 ;
int c[maxn+10], cnt[maxn+10] ;
int lowbit(int x){
    return x & (-x) ;
}
void update(int pos){
    while(pos<=maxn){
        c[pos] ++ ;
        pos += lowbit(pos) ;
    }
}
int query(int pos){
    int s = 0 ;
    while(pos>0){
        s += c[pos] ;
        pos -= lowbit(pos) ;
    }
    return s ;
}
int main(){
    int n, i, j, x, y ;
    while(~SD(n)){
        SET(c, 0) ;
        SET(cnt, 0) ;
        FF(i, n){
            SSD(x, y) ;
            x ++ ;
            cnt[query(x)] ++ ;
            update(x) ;
        }
        FF(i, n)    PF(cnt[i]) ;
    }
    return 0 ;
}

抱歉!评论已关闭.