Cows(poj 2481 树状数组)

时间:2024-05-20 15:36:26
Cows
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 15301   Accepted: 5095

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.
题意:两个区间:[Si, Ei] and [Sj, Ej].(0 <= S < E <= 105). 若 Si <= Sj and Ej <= Ei and Ei – Si > Ej – Sj, 则第i个区间覆盖第j个区间。给定N个区间(1 <= N <= 10^5),分别求出对于第i个区间,共有多少个区间能将它覆盖。

思路:初看好像挺复杂的。其实可以把区间[S, E]看成点(S, E),这样题目就转化为hdu 1541 Stars。只是这里是求该点左上方的点的个数。

虽然如此,我还是WA了不少,有一些细节没注意到。给点排序时是先按y由大到小排序,再按x由小到大排序。而不能先按x排序。比如n=3, [1,5], [1,4], [3,5]的例子。另外还要注意对相同点的处理。

 #include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std; const int MAX = ; struct Node{
int x, y, id, ans;
}seq[MAX];
int sum[MAX], n; int cmp1(Node a,Node b){
if(a.y==b.y) return a.x<b.x;
return a.y>b.y;
}
int cmp2(Node a,Node b){
return a.id<b.id;
} int lowbit(int x){
return x & (-x);
}
void add(int pos, int val){
while(pos < MAX){
sum[pos]+=val;
pos+=lowbit(pos);
}
}
int getsum(int pos){
int res = ;
while(pos>){
res+=sum[pos];
pos-=lowbit(pos);
}
return res;
} int main()
{
freopen("in.txt","r",stdin);
int i,j;
while(scanf("%d", &n) && n){
for(i=;i<=n;i++){
scanf("%d%d", &seq[i].x, &seq[i].y);
seq[i].x++, seq[i].y++;
seq[i].id = i;
}
sort(seq+,seq+n+,cmp1);
memset(sum, , sizeof(sum));
seq[].ans = ;
add(seq[].x, );
int fa = ;
for(i=;i<=n;i++){
if(seq[i].x == seq[fa].x && seq[i].y == seq[fa].y){
seq[i].ans = seq[fa].ans;
}else{
fa = i;
seq[i].ans = getsum(seq[i].x);
} add(seq[i].x, );
}
sort(seq+,seq+n+,cmp2);
printf("%d", seq[].ans);
for(i=;i<=n;i++) printf(" %d", seq[i].ans);
printf("\n");
}
return ;
}