树状数组专题(三)POJ2481

来源:互联网 发布:手机新浪博客网络异常 编辑:程序博客网 时间:2024/05/29 18:18
//这里有几个需要学习的东西.
//1..如何对结构体进行调用排序函数的operator的操作构造
//2..如何把这个题目转换成为树状数组的思维..
//3..如何去记录一个数组排序前的位置..在结构体里面加一个元素记录原来的位置.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int MN = 110000;
struct Cow
{
    int s,e,value;
    Cow(){};
    bool operator < (const Cow &tmp)  const
    {
        if(e > tmp.e)return 1;
        if(e < tmp.e)return 0;
        if(e == tmp.e)
        {
            if(s > tmp.s)return 0;
            else return 1;
        }
    }
};
Cow test[MN];int maxx;
int tree[MN],b[MN],ans[111111],c[MN],exchan[MN];
int Lowbit(int x)
{
    return x&(-x);
}
void Updata(int x)
{
    if(x <= 0)return;
    for(int i = x ; i <= maxx ; i += Lowbit(i))
    {
        tree[i]++;
    }
}
int Getsum(int x)
{
    int sum = 0 ;
    while(x > 0)
    {
        sum += tree[x];
        x -= Lowbit(x);
    }
    return sum;
}
int main()
{
    int n;
    while(scanf("%d",&n) && n != 0)
    {
        maxx = 0;
        memset(tree,0,sizeof(tree));
        for(int i = 1 ; i <= n ; i++)
        {
            scanf("%d%d",&test[i].s,&test[i].e);
            test[i].s++;
            test[i].value = i;
            maxx = max(maxx,test[i].s);
        }
        sort(test + 1, test + n + 1);
        for(int i = 1 ; i <= n ; i++)
        {
            if(test[i].s == test[i-1].s && test[i].e == test[i-1].e && i > 1)
            ans[test[i].value] = ans[test[i-1].value];
            else
            ans[test[i].value] = Getsum(test[i].s);
            Updata(test[i].s);
        }
        for(int i = 1 ; i <= n ; i++)
        {
            printf("%d ",ans[i]);
        }
        printf("\n");
    }
}
原创粉丝点击