您的位置:首页 > 其它

poj 2481 树状数组

2013-08-22 20:34 218 查看
一开始根本没想到是树状数组,因为有两个端点需要处理,后来经提醒,排序后只剩下一个端点,接下来树状数组就ok了。

注意:题目中下标从0开始,所以输入后都要加1,以满足树状数组下标从1开始的性质。

排序后一个一个处理,前面的比后面强壮,或区间相同,处理时排除区间相同的即可。

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
inline void RD(int &ret)
{
char c;
do
{
c=getchar();
}while(c<'0'||c>'9');
ret=c-'0';
while((c=getchar())>='0'&&c<='9')
ret=ret*10+(c-'0');
}
inline void OT(int a)
{
char c;
if(a>=10)
{
OT(a/10);
}
putchar(a%10+'0');
}
struct node
{
int b,e;
int pos;
}s[100005],pre;
int n;
int c[100005];
int re[100005];
bool cmp(node x,node y)
{
if(x.e==y.e)
return x.b<y.b;
else
return x.e>y.e;
}
int lowbit(int x)
{
return x&(-x);
}
void add(int i,int detal)
{
while(i<=100002)
{
c[i]+=detal;
i+=lowbit(i);
}
}
int sum(int k)
{
int ret=0;
while(k>0)
{
ret+=c[k];
k-=lowbit(k);
}
return ret;
}
int main()
{
while(scanf("%d",&n)&&n)
{
memset(c,0,sizeof(c));
//memset(re,0,sizeof(re));
for(int i=1;i<=n;i++)
{
scanf("%d%d",&s[i].b,&s[i].e);
s[i].pos=i;
s[i].b+=1;
s[i].e+=1;
}
sort(s+1,s+1+n,cmp);

pre.b=-1;
pre.e=-1;
int ans=0;
//因为经过排序后后面没有比前面还强大的,所以一个一个处理
//ans的记录也很神奇,排除排序区间相同的
for(int i=1;i<=n;i++)
{
if(s[i].b==pre.b&&s[i].e==pre.e) ans++;
else
{
ans=0;
pre.b=s[i].b;
pre.e=s[i].e;
}
re[s[i].pos]=sum(s[i].b)-ans;
add(s[i].b,1);
}
for(int i=1;i<=n;i++)
{
printf("%d ",re[i]);
}
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: