POJ 2481 cows 树状数组

题意很简单,需要注意的一点是当两头牛的range完全相同的时候后面的牛的Strongnumber==前面牛的Strongnumber,效率不是很高,2200+ms

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include <iostream>
using namespace std;
typedef struct
{
	int x;
	int y;
	int index;
}cow;
cow cows[100010];
int N;
int tree[100010];
int ans[100010];
bool cmp(cow c,cow d)
{
	if(c.y==d.y)
	{
		return c.x<d.x;
	}
	return c.y>d.y;
}
int lowbit(int x){return x&(-x);}
void update(int index)
{
	while(index<=100010)
	{
		tree[index]++;
		index+=lowbit(index);
	}
}
int getsum(int index)
{
	int sum=0;
	while(index>0)
	{
		sum+=tree[index];
		index-=lowbit(index);
	}
	return sum;
}
int main()
{
	setbuf(stdout,NULL);
	int i,start,end;
	while(scanf("%d",&N)!=EOF)
	{
		if(N==0)break;
		memset(tree,0,sizeof(tree));
        for(i=0;i<N;i++)
        {
        	scanf("%d%d",&start,&end);
        	cows[i].index=i;
        	cows[i].x=++start;
        	cows[i].y=end;
        }

        sort(cows,cows+N,cmp);

        for(i=0;i<N;i++)
        {
        	if(cows[i].x==cows[i-1].x&&cows[i].y==cows[i-1].y)
        	{
        		ans[cows[i].index]=ans[cows[i-1].index];

        	}
        	else
        	{
        		ans[cows[i].index]=getsum(cows[i].x);
        	}

        	update(cows[i].x);
        }
        for(i=0;i<N-1;i++)
        {
        	printf("%d ",ans[i]);
        }
        printf("%d\n",ans[N-1]);
	}
	return 0;
}

posted on 2011-07-23 09:46  lonelycatcher  阅读(347)  评论(0编辑  收藏  举报

导航