您的位置:首页 > 其它

POJ 2481 Cows 树状数组

2016-09-08 10:53 579 查看
Cows

Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 16964 Accepted: 5681
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


题目大意:

给出 n 个区间,输出  每个 区间被 多少个 区间包含。

思路:

如果我们按照 区间终点从大到小排列,区间的起点从小到大排列,那么我们这个问题就可以转化为统计 插入的 第 i 个区间,在他之间,起点比它小的区间的个数。这样的话,就可以用树状数组来解决这个问题。

如果没明白请多读几遍,或者模拟一下。

AC代码:

#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
const int MAXN=100005;
int a[MAXN];
int level[MAXN];
struct qqq
{
int s;
int e;
int pos;
friend bool operator < (const qqq &a,const qqq &b)
{
if(a.e==b.e)
return a.s<b.s;
return a.e>b.e;
}
}num[MAXN];
int	lowbit(int	x)
{
return	x&(-x);
}
void add(int x)
{
while(x<=MAXN)
{
a[x]++;
x+=lowbit(x);
}
}
int	get_sum(int	x)
{
int	ret=0;
while(x>0)
{
ret+=a[x];
x-=lowbit(x);
}
return	ret;
}
int main()
{
int n;
int x,y;
while(scanf("%d",&n),n)
{
memset(a,0,sizeof(a));
memset(level,0,sizeof(level));
for(int i=1;i<=n;i++)
{
scanf("%d%d",&num[i].s,&num[i].e);
num[i].pos=i;
}
sort(num+1,num+n+1);
level[num[1].pos]=0;
add(num[1].s+1);
for(int i=2;i<=n;i++)
{
if(num[i].e==num[i-1].e&&num[i].s==num[i-1].s)
{
level[num[i].pos]=level[num[i-1].pos];
}
else
{
level[num[i].pos]=get_sum(num[i].s+1);
}
add(num[i].s+1);
}
for(int i=1;i<=n;i++)
{
printf("%d ",level[i]);
}
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 树状数组