树状数组 之 poj 2352

//  [5/9/2014 Sjm]
/*
解题关键:
(1) Let the level of a star be an amount of the stars that are not higher and not to the right of the given star.
    这个便是对 lev[i] 的定义
(2) Stars are listed in ascending order of Y coordinate. 
    Stars with equal Y coordinates are listed in ascending order of X coordinate.
    星星在输入时,是按 y 的递增顺序,如若 y 相同则按 x 升序
    故后面的星星不影响前面的星星的 lev,在使用舒张数组时只考虑 x 即可
(3) 0<=X,Y<=32000
    由于 x 可以等于 0,树状数组下标不能为 0 (若包含0,则在求 sum 时,0 == (0 & (-0)) 陷入死循环,可参见代码)
    故在每次使用 x 时,x 默认 +1
   (因为这个 TLE 了好多次,还是要多做题啊。。。)
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX_X_Y = 32002, MAX_N = 15000;
int n, myBit[MAX_X_Y], lev[MAX_N];

int mySum(int i)
{
    int s = 0;
    while (i) {
        s += myBit[i];
        i -= (i & (-i));
    }
    return s;
}

void myAdd(int i)
{
    while (i<MAX_X_Y) {
        myBit[i] += 1;
        i += (i & (-i));
    }
}

int main()
{
    //freopen("input.txt", "r", stdin);
    while (~scanf("%d", &n))
    {
        memset(myBit, 0, sizeof(myBit));
        memset(lev, 0, sizeof(lev));
        for (int i=0; i<n; i++)
        {
            int x, y;
            scanf("%d %d", &x, &y);
            x++;
            lev[mySum(x)]++;
            myAdd(x);
        }
        for (int i=0; i<n; i++)
        {
            printf("%d
", lev[i]);
        }
    }
	return 0;
}


原文地址:https://www.cnblogs.com/shijianming/p/4140850.html