您的位置:首页 > 理论基础 > 数据结构算法

poj 2481 cows 树状数组

2016-07-08 14:38 543 查看
Cows
Time Limit: 3000MS

 

Memory Limit: 65536K

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: cowi and cowj, their favourite clover range is [Si, Ei] and [Sj, Ej]. If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, we say that cowi is stronger than cowj. 

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 <= 105), which is the number of cows. Then come N lines, the i-th of which contains two integers: S and E(0 <= S < E <= 105) 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 cowi. 

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.

 

题意:求每个区间是多少个区间的真子集

借用hdu 1541 stars的思想,

把这些区间的左右端点分别看成坐标的x和y值,然后先按y轴从大到小排,其次,y相等再按x从小到大排,最后依次读入每个点,那么这个点左上方的点的个数就是包含它的区间个数.

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

int maxn=100001;
struct node
{
int x,y;
int n;
} nod[100001];
int c[100001],ans[100001];
int lowbit(int x)
{
return x&(-x);
}
void up(int x,int val)
{
for(; x<=maxn; x+=lowbit(x)) c[x]+=val;
}

int sum(int x)
{
int sum=0;
for(; x>0; x-=lowbit(x)) sum+=c[x];
return sum;
}
inline bool cmp(const node a,const node b)
{
if(a.y!=b.y) return a.y>b.y;//y不同就按y从大到小排
return a.x<b.x;//y相同就按x从小到大排
}
int main()
{
int x,j,i,n;
while(~scanf("%d",&n)&&n)
{
memset(c,0,sizeof(c));
maxn=n;
for(i=1; i<=n; i++)
{
scanf("%d %d",&nod[i].x,&nod[i].y);
nod[i].n=i;
}
sort(nod+1,nod+n+1,cmp);
for(i=1; i<=n; i++)
{

if (nod[i].x== nod[i - 1].x && nod[i].y== nod[i - 1].y)//如果两点重合,因为是真子集,那么后一个点和前一个点的值应该相同,不能加一
{
ans[nod[i].n] = ans[nod[i - 1].n];
}
else
ans[nod[i].n] = sum(nod[i].x+ 1);
up(nod[i].x+ 1,1);
}
for(i=1; i<n; i++)
printf("%d ",ans[i]);
printf("%d\n",ans[i]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息