Codeforces 652D Nested Segments 【树状数组 + 离散化】

题目链接:Codeforces 652D Nested Segments

D. Nested Segments
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard 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

题意:给定n个区间,问你第i个区间包含多少个区间。

类似POJ2481。。。就多了个离散化。。。

AC 代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define PI acos(-1.0)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define fi first
#define se second
#define ll o<<1
#define rr o<<1|1
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int MAXN = 2*1e5 + 10;
const int pN = 1e6;// <= 10^7
const int INF = 0x3f3f3f3f;
const int MOD = 2009;
void add(LL &x, LL y) { x += y; x %= MOD; }
int C[MAXN*2];
struct Node {
    int x, y, id;
};
Node num[MAXN];
int N;
bool cmp(Node a, Node b) {
    return a.y != b.y ? a.y < b.y : a.x > b.x;
}
int lowbit(int x) {
    return x & (-x);
}
void add(int x, int d) {
    while(x <= N) {
        C[x] += d;
        x += lowbit(x);
    }
}
int Sum(int x) {
    int s = 0;
    while(x > 0) {
        s += C[x];
        x -= lowbit(x);
    }
    return s;
}
int ans[MAXN], rec[MAXN*2];
int main()
{
    int n; scanf("%d", &n); int top = 0; N = 2 * n;
    for(int i = 1; i <= n; i++) {
        scanf("%d%d", &num[i].x, &num[i].y);
        num[i].id = i;
        rec[top++] = num[i].x; rec[top++] = num[i].y;
    }
    sort(rec, rec+top); int m = unique(rec, rec+top) - rec;
    sort(num+1, num+n+1, cmp); CLR(C, 0);
    for(int i = 1; i <= n; i++) {
        int l = lower_bound(rec, rec+m, num[i].x) - rec;
        int r = lower_bound(rec, rec+m, num[i].y) - rec;
        l++; r++;
        //cout << l << ' ' << r << endl;
        ans[num[i].id] = Sum(r) - Sum(l-1);
        add(l, 1);
    }
    for(int i = 1; i <= n; i++) {
        printf("%d\n", ans[i]);
    }
    return 0;
}

你可能感兴趣的:(树状数组,离散化,codeforces)