您的位置:首页 > 其它

POJ 2481 Cows 树状数组

2013-07-28 20:23 330 查看
/**
*    树状数组:
*    其实这题和 POJ 2352 或者 就是道用树状数组求逆序数的题目。
*    先排序,我的排序是按照先s从小到大,如果s相等 e从大到小。
*    貌似也没什么了。就树状数组吧。。。
*/

#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
#define INF 0x7fffffff
#define MAXS 100005
#define LL long long
using namespace std;
int ans[MAXS], c[MAXS];
struct Cow {
    int s, e, ans, NO;
    bool operator < (const Cow &a) const {
        if(s != a.s)
            return s < a.s;
        return e > a.e;
    }
} cows[MAXS];

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

void cal(int x) {
    int ret = 0;
    if(cows[x].e == cows[x - 1].e && cows[x].s == cows[x - 1].s)
        ans[cows[x].NO] = ans[cows[x - 1].NO];
    else {
        for(int i = cows[x].e - 1; i > 0; i -= lowbit(i)) {
            ret += c[i];
        }
        ans[cows[x].NO] = x - ret - 1;
    }
}

void update(int x, int n) {
    for(int i = cows[x].e; i <= n; i += lowbit(i)) {
        c[i] ++;
    }
}

int main()
{
    int n;
    while(scanf("%d", &n), n) {
        memset(c + 1, 0, sizeof(int) * n);
        for(int i = 1; i <= n; i ++) {
            scanf("%d%d", &cows[i].s, &cows[i].e);
            cows[i].NO = i;
        }
        sort(cows + 1, cows + n + 1);
        for(int i = 1; i <= n; i ++) {
            cal(i);
            update(i, n);
        }
        printf("%d", ans[1]);
        for(int i = 2; i <= n; i ++)
            printf(" %d", ans[i]);
        printf("\n");
    }

    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: