您的位置:首页 > 其它

POJ2481 Cows 树状数组

2017-03-05 22:49 260 查看
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

树状数组 开一个结构体 排序求逆序对
注意0的时候(如果没有做过的话可以先想想怎么解决 看代码一下就能懂)不要再T了(不明白的话想一想当x=0的时候那个calc的lowbit一直是在循环) 吃一堑长一智 这次注意到了
但是.... 注意题意If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj 比如说两头完全一样的牛 1 2 和 1 2 应该输出0 0
而不是0 1 一开始大概做了一下发现一直WA.. 要注意细节啊啊啊啊
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int N=100005;
struct node
{
int l,r,id;
} a
;
int n,maxn,c
,ans
;
int lowbit(int x)
{
return x&(-x);
}
int cmp(const node &a,const node &b)
{
if(a.r!=b.r) return a.r>b.r;
else return a.l<b.l;
}

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

void update(int x,int d)
{
while(x<=maxn+1)
{
c[x]+=d;
x+=lowbit(x);
}
}
int main()
{
while(~scanf("%d",&n),n)
{
memset(c,0,sizeof(c));
maxn = -1;
for(int i = 1; i<=n; i++)
{
scanf("%d%d",&a[i].l,&a[i].r);
a[i].id = i;
maxn = max(maxn,a[i].r);
}
sort(a+1,a+1+n,cmp);
for(int i = 1; i<=n; i++)
{
if(a[i].l == a[i-1].l && a[i].r == a[i-1].r)
{
ans[a[i].id] = ans[a[i-1].id];
}
else
{
ans[a[i].id] = sum(a[i].l+1);
}
update(a[i].l+1,1);
}
for(int i=1;i<=n;i++)
{
printf("%d%c",ans[i],i<n?' ':'\n');
}
}
return 0;
}



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