树状数组之三

//poj 2481 Cows

#include
<iostream> //树状数组
#include <algorithm>
using namespace std;
const int maxn=100005;
int table[maxn],num[maxn],repeat[maxn],n,i;
struct Cow
{
int st,ed;
int pos;
bool operator<(const Cow& c) const //ed按降序排,若相同则按st升序排;用一维的树状数组table[]来处理。
{
if(ed==c.ed)
return st<c.st;
else
return ed>c.ed;
}
}cow[maxn];
void overlap() //处理重区间
{
for(i=1;i<n;++i)
if(cow[i].ed==cow[i-1].ed&&cow[i].st==cow[i-1].st)
repeat[i]
=repeat[i-1]+1;
}
int lowbit(int x)
{
return x&(-x);
}
void modify(int x)
{
while(x<maxn)
{
table[x]
++;
x
+=lowbit(x);
}
}
int sum(int x)
{
int s=0;
while(x>0)
{
s
+=table[x];
x
-=lowbit(x);
}
return s;
}
int main()
{
while(scanf("%d",&n)&&n)
{
memset(repeat,
0,sizeof(repeat));
memset(num,
0,sizeof(num));
memset(table,
0,sizeof(table));
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++; //保证下标永远不为0 ,因为lowbit(0)=0,会给运算带来麻烦
}
sort(cow,cow
+n);
overlap();
for(i=0;i<n;++i)
{
num[cow[i].pos]
=sum(cow[i].st)-repeat[i]; //找出比当前cow更壮的cow的数目
modify(cow[i].st);
}
for(i=0;i<n;++i)
printf(
"%d ",num[i]);
printf(
"\n");
}
return 0;
}

  

posted on 2011-07-17 01:53  sysu_mjc  阅读(85)  评论(0编辑  收藏  举报

导航