poj 2481 Cows

// 题意:有n头奶牛,各自有属性[s,e],假如Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, 则牛 i 比牛 j 强壮
// 询问每头奶牛比他强的奶牛的数量

#include <iostream> //一维树状数组
#include <algorithm>
using namespace std;
const int maxn=100005;
int table[maxn],tail; //table表示树状数组,下标从 1 到 tail
int overlap[maxn],ans[maxn];

struct Cow
{
int st,ed;
int pos; //标记在原序列中的位置
bool operator<(const Cow& c) const //ed按降序排,若相同则按st升序排
{
if(ed==c.ed)
return st<c.st;
else
return ed>c.ed;
}
}cow[maxn];
int lowbit(int x)
{
return x&(-x);
}
void modify(int x)
{
while(x<=tail)
{
table[x]++; //计数加 1
x+=lowbit(x);
}
}
int sum(int x)
{
int s=0;
while(x>0)
{
s+=table[x];
x-=lowbit(x);
}
return s;
}
int main()
{
int n;
while(scanf("%d",&n)&&n)
{
tail=0;
int i;
for(i=0;i<n;++i)
{
cow[i].pos=i;
scanf("%d%d",&cow[i].st,&cow[i].ed);
cow[i].st++;cow[i].ed++; //让数组下标从 1开始
tail=max(tail,cow[i].st);
}
sort(cow,cow+n);
for(i=1;i<n;++i) //标记重叠区间
{
if(cow[i].ed==cow[i-1].ed&&cow[i].st==cow[i-1].st)
overlap[i]=overlap[i-1]+1;
else
overlap[i]=0;
}
memset(table,0,sizeof(table));
for(i=0;i<n;++i)
{
ans[cow[i].pos]=sum(cow[i].st)-overlap[i]; //找出比当前cow更壮的cow的数目
modify(cow[i].st); //更新数据
}
for(i=0;i<n;++i)
printf("%d ",ans[i]);
printf("\n");
}
return 0;
}

posted on 2011-07-22 16:34  sysu_mjc  阅读(124)  评论(0编辑  收藏  举报

导航