您的位置:首页 > 其它

POJ 2481 Cows 树状数组

2016-08-23 15:44 351 查看
Description

Farmer John's cows have discovered that the clover growing along the ridge of the hill (which we can think of as a one-dimensional number line) in his field is particularly good. 

Farmer John has N cows (we number the cows from 1 to N). Each of Farmer John's N cows has a range of clover that she particularly likes (these ranges might overlap). The ranges are defined by a closed interval [S,E]. 

But some cows are strong and some are weak. Given two cows: cow i and cow j, their favourite clover range is [Si, Ei] and [Sj, Ej]. If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, we say that cow i is stronger than cow j. 

For each cow, how many cows are stronger than her? Farmer John needs your help!

Input

The input contains multiple test cases. 

For each test case, the first line is an integer N (1 <= N <= 10 5), which is the number of cows. Then come N lines, the i-th of which contains two integers: S and E(0 <= S < E <= 10 5) specifying the start end location respectively of
a range preferred by some cow. Locations are given as distance from the start of the ridge. 

The end of the input contains a single 0.

Output

For each test case, output one line containing n space-separated integers, the i-th of which specifying the number of cows that are stronger than cow i. 

Sample Input

3
1 2
0 3
3 4
0


Sample Output

1 0 0


Hint

Huge input and output,scanf and printf is recommended.

这题可以转化成如果按照s从小到大,e从大到小排好的话,每一种情况所对应的比他强壮的就只需要看此时有多少e大于等于他的e就行了。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

const int n=100000+5;

struct node
{
int s,e;
int pos;
}pow[n+1];

int c[n+1];
int ans[n+1];

int cmp(node x,node y)
{
if(x.s!=y.s)
return x.s<y.s;
else
return x.e>y.e;
}

int lowbit(int k)
{
return (k&(-k));
}

int sum(int x) //求和
{
int ret = 0;
while(x>0)
{
ret+=c[x];
x-=lowbit(x);
}
return ret;
}

void add(int x,int d) //修改节点的值
{
while(x<=n)
{
c[x]+=d;
x+=lowbit(x);
}
}

int main()
{
int t;
int i,j;
while(~scanf("%d",&t)&&t)
{
memset(c,0,sizeof(c));
memset(ans,0,sizeof(ans));
for(i=0;i<t;i++)
{
scanf("%d%d",&pow[i].s,&pow[i].e);
pow[i].pos=i;
}
sort(pow,pow+t,cmp);
for(i=0;i<t;i++)
{
if(pow[i].s!=pow[i-1].s||pow[i].e!=pow[i-1].e)
{
ans[pow[i].pos]=sum(n)-sum(pow[i].e-1);
add(pow[i].e,1);
}
else
{
ans[pow[i].pos]=ans[pow[i-1].pos];
add(pow[i].e,1);
}
}
for(i=0;i<t-1;i++)
{
printf("%d ",ans[i]);
}
printf("%d\n",ans[i]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: