Codeforces 652D Nested Segments 树状数组离线处理

来源:互联网 发布:法院网络拍卖 编辑:程序博客网 时间:2024/05/18 16:54

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.

Example
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

求出每个区间内包含了几个完整的子区间。按照左坐标从大到小排序,再按顺序将区间的右坐标加入数组,由于未加入的区间左坐标在已加入的左边,肯定不被包含,而已经加入数组的都是左坐标符合条件的,之后只要区间查询包含了几个右坐标,就能知道包含了几个子区间而且没有遗漏

#include <iostream>#include <stdio.h>#include <map>#include <set>#include <queue>#include <algorithm>#include <vector>#include <math.h>#include <iterator>#include <string.h>using namespace std;typedef long long ll;int mo[4][2]={0,1,1,0,0,-1,-1,0};const int MAXN=0x3f3f3f3f;const int sz=200005;int n;struct node{    int l,r,num;}a[sz];struct number{    int num,v;}hs[sz*2];bool cmp(node x,node y){    return x.l>y.l;}bool cmpnum(number x,number y){    return x.v<y.v;}int tr[sz*2];int ans[sz];void add(int x){    for(;x<=2*n;x+=x&(-x)){        tr[x]++;    }}int sum(int x){    int s=0;    for(;x>0;x-=x&(-x)){        s+=tr[x];    }    return s;}int query(int x,int y){    return sum(y)-sum(x-1);}int main(){    //freopen("C:\\Users\\Administrator\\Desktop\\r.txt","r",stdin);    while(scanf("%d",&n)!=EOF){        memset(tr,0,sizeof(tr));        for(int i=1;i<=n;i++){            scanf("%d%d",&a[i].l,&a[i].r);            a[i].num=i;            hs[i].v=a[i].l;            hs[i].num=i;            hs[i+n].v=a[i].r;            hs[i+n].num=i+n;        }        sort(hs+1,hs+1+2*n,cmpnum);        for(int i=1;i<=2*n;i++){            if(hs[i].num<=n)                a[hs[i].num].l=i;            else                a[hs[i].num-n].r=i;        }        sort(a+1,a+1+n,cmp);        for(int i=1;i<=n;i++){            ans[a[i].num]=query(a[i].l,a[i].r);            add(a[i].r);        }        for(int i=1;i<=n;i++){            printf("%d\n",ans[i]);        }    }    return 0;}
原创粉丝点击