您的位置:首页 > 其它

CF652 树状数组,离散化,子区间问题

2016-04-16 17:22 399 查看
D. Nested Segments

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it
contains.

Input

The first line contains a single integer n (1 ≤ n ≤ 2·105)
— the number of segments on a line.

Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ri ≤ 109)
— the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that
coincide.

Output

Print n lines. The j-th
of them should contain the only integer aj —
the number of segments contained in the j-th segment.

Examples

input
4
1 8
2 3
4 7
5 6


output
3
0
1
0


input
3
3 4
1 5
2 6


output
0
1
1

http://codeforces.com/contest/652/problem/D
题目大意:

给n个区间,问,每个区间内有几个小区间(这些区间都是n个区间内的)。

思路:

由于坐标很大,但是n是2*100000,所以我们考虑离散化坐标。

首先,我们离散化所有的区间,然后我们用vector将所有的区间都包含在里面,排序后用二分对其全部都进行离散化。

接来下,我们以右端为基础,有树状数组来维护所有右端的值即可。

然后我们再以左端为主,然后进行排序,因为排序后已经保证了ai<ai+1,所以,我们只需要考虑树状数组中,右端比它小的就可以了。

#include

using namespace std;

const int maxn = 2 * 100000 + 5;
int n;
int val[maxn];
pair , int> p[maxn];
vector  v;
int ind[maxn * 4];

void init(){
scanf("%d", &n);
for (int i = 0; i < n; i++){
int l, r;
scanf("%d %d", &l, &r);
p[i] = make_pair(make_pair(l, r), i);
v.push_back(l);
v.push_back(r);
}
}

void query(int x, int add){
while (x <= v.size()){
ind[x] += add;
x += (x & -x);
}
}

int sum(int x){
int res = 0;
while (x > 0){
res += ind[x];
x -= (x & -x);
}
return res;
}

void solve(){
sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());
for (int i = 0; i < n; i++){
p[i].first.first = lower_bound(v.begin(), v.end(), p[i].first.first) - v.begin() + 1;
p[i].first.second = lower_bound(v.begin(), v.end(), p[i].first.second) - v.begin() + 1;
query(p[i].first.second, 1);
}
sort(p, p + n);
/*for (int i = 0; i < n; i++){
printf("p.second = %d\n", p[i].second);
printf("%d %d\n", p[i].first.first, p[i].first.second);
}*/
for (int i = 0; i < n; i++){
query(p[i].first.second, -1);
val[p[i].second] = sum(p[i].first.second);
}
for (int i = 0; i < n; i++){
printf("%d\n", val[i]);
}
}

int main(){
init();
solve();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: