您的位置:首页 > 其它

POJ 2481 Cows 【树状数组】

2015-11-27 16:22 204 查看

Cows

Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 15245Accepted: 5078
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.

恩,题目大意就是说,每头奶牛都有它自己的草地领地范围,可能会重合,然后若另一头牛的领地范围包括了该牛的,则成另一头牛比该牛强大。现在要对每一头牛求比它强大的牛的个数,不包括和它相等的。先对 y 进行非递减排序,在此基础上对 x 进行非递增排序,要考虑区间相等的情况,对它不进行重复求和,而要更新,看代码吧。

#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 100010
using namespace std;
int Max,c[maxn],l[maxn];
struct node
{
int s,e,f;
};
node r[maxn];
int cmp(node a,node b)
{
if(a.e!=b.e)
return a.e<b.e;
return a.s>b.s;
}
int lowbit(int t)
{
return t&(t^(t-1));
}
void update(int x)
{
for(int i=x;i<=Max+1;i+=lowbit(i))
c[i]++;
}
int sum(int x)
{
int ans=0;
for(int i=x;i>0;i-=lowbit(i))
ans+=c[i];
return ans;
}
int main()
{
int n;
while(scanf("%d",&n),n)
{
Max=-1;
memset(c,0,sizeof(c));
memset(l,0,sizeof(l));
for(int i=0;i<n;++i)
{
scanf("%d%d",&r[i].s,&r[i].e);
r[i].f=i;
Max=max(Max,r[i].e);
}
sort(r,r+n,cmp);
for(int i=n-1;i>=0;i--)
{
if(r[i].s==r[i+1].s&&r[i].e==r[i+1].e)
{
l[r[i].f]=l[r[i+1].f];
}
else
l[r[i].f]=sum(r[i].s+1);
update(r[i].s+1);
}
for(int i=0;i<n;++i)
{
if(i)
printf(" %d",l[i]);
else
printf("%d",l[i]);
}
printf("\n");
}
return 0;
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: