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: cow i and cow j, their favourite clover range is [Si, Ei] and [Sj, Ej]. If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, we say that cow i is stronger than cow j.
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 <= 10 5), which is the number of cows. Then come N lines, the i-th of which contains two integers: S and E(0 <= S < E <= 10 5) 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 cow i.
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.
就是用树状数组做的一道题,首先讲右边界排序(从大到小),然后按照排序顺序遍历,对于每个区间的左边界,统计比他大的左边界个数, 并记录。`
#include<iostream>
#include <stdio.h>
#include <cmath>
#include <cstring>
#include <string.h>
#include <algorithm>
using namespace std;
#define Max_N 100000+20
struct point
{
int x, y;
int i;
};
bool cmp(const point &a, const point &b )
{
if(a.y == b.y) return a.x < b.x;
else return a.y > b.y;
}
point d[Max_N];
int c[Max_N];
int level[Max_N];
int n;
int Max;
int low(int x)
{
return x&-x;
}
int sum(int x)
{
int res = 0;
while(x > 0)
{
res += c[x];
x -= low(x);
}
return res;
}
int add(int i)
{
while(i <= Max+2) {
c[i]++;
i += low(i);
}
return 0;
}
int main()
{
while(scanf("%d", &n) &&n) {
Max = -1;
for (int i = 0; i < n; i++) {
scanf("%d%d", &d[i].x, &d[i].y);
d[i].i = i+1;
Max = max(Max, d[i].y);
}
memset(c, 0, sizeof(c));
sort(d, d+n, cmp);
/*for (int i = 0; i < n; i++)
cout << d[i].x << " " << d[i].y << endl;*/
level[d[0].i] = 0;
add(d[0].x+1);
for (int i = 1; i < n; i++) {
if(d[i].x == d[i-1].x && d[i].y == d[i-1].y)
level[d[i].i] = level[d[i-1].i];
else level[d[i].i] = sum(d[i].x+1);
add(d[i].x+1);
// cout << "ss" <<endl;
}
for (int i = 1; i <= n; i++) {
if(i == 1) printf("%d", level[i]);
else printf(" %d", level[i]);
}
printf("\n");
}
return 0;
}