您的位置:首页 > 其它

CodeForce 652D Nested Segments 树状数组

2016-04-20 20:24 316 查看
D. Nested Segments
time limit pertest
2 seconds
memory limit pertest
256 megabytes
input
standard input
output
standard output
You are given n segments on aline. There are no ends of some segments
that coincide. For each segment findthe number of segments it contains.
Input
The first linecontains a single integer n (1 ≤ n ≤ 2·105)
— the numberof segments on a line.
Each of the next n lines containstwo integers li and ri ( - 109 ≤ li < ri ≤ 109)
— thecoordinates of the left and the right ends of the i-th segment. Itis guaranteed that there are no ends of some segments that coincide.
Output
Print n lines. The j-th
of themshould contain the only integer aj — the number ofsegments
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

/*
思路:端点以左端点从大到小排序,这样,每一次求解答案的时候都只能在左端点比它大的线段中找
但是,题目数据比较大,我们用树状数组来优化
另外,我们必须先将右端点离散化来处理
所以,每次求解一个线段的答案 都是找右端点r在树状数组中1~r区间的值
*/

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn = 2e5 + 5;
int n, sum[maxn] = { 0 }, ans[maxn];
struct node
{
int l, r, id;
}tree[maxn];

bool cmp1(struct node x, struct node y)  //左端点从大到小
{
if (x.l == y.l) return x.r < y.r;
return x.l > y.l;
}

bool cmp2(struct node x, struct node y)	//右端点从小到大
{
if (x.r == y.r) return x.l > y.l;
return x.r < y.r;
}

void update(int x)
{
while (x <= n)
{
sum[x]++;
x += x&-x;
}
}

int query(int x)
{
int s = 0;
while (x)
{
s += sum[x];
x -= x&-x;
}
return s;
}

int main()
{
while (scanf("%d", &n) != EOF)
{
memset(sum, 0, sizeof(sum));
for (int i = 1; i <= n; i++)
{
scanf("%d%d", &tree[i].l, &tree[i].r);
tree[i].id = i;
}
sort(tree + 1, tree + 1 + n, cmp2);
for (int i = 1; i <= n; i++)
tree[i].r = i;
sort(tree + 1, tree + 1 + n, cmp1);		//左端点最右的一定没有子线段

for (int i = 1; i <= n; i++)
{
ans[tree[i].id] = query(tree[i].r);
update(tree[i].r);
}

for (int i = 1; i <= n; i++)
printf("%d\n", ans[i]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: