http://www.cnblogs.com/kevince/p/3893531.html
線段樹,需要離散化
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#define lson rt << 1, l, m
#define rson rt << 1 | 1, m + 1, r
const int MAXN = 20005;
typedef int ll;
using namespace std;
struct Node
{
ll l, r, num, lazy;
ll mid() { return (l + r) >> 1; }
void setPara(int ll, int rr, int nn, int lz) { l = ll, r = rr, num = nn, lazy = lz; }
} Tree[MAXN * 4];
void buildTree(int rt, int l, int r)
{
Tree[rt].setPara(l, r, r - l + 1, 0);
if (l == r)
return;
ll m = Tree[rt].mid();
buildTree(lson);
buildTree(rson);
}
void push_up(int rt)
{
Tree[rt].num = max(Tree[rt << 1].num, Tree[rt << 1 | 1].num);
}
bool query(int rt, int l, int r)
{
if (Tree[rt].num == 0)
return false;
if (l <= Tree[rt].l && Tree[rt].r <= r)
{
Tree[rt].num = 0;
return true;
}
bool ret = false;
ll m = Tree[rt].mid();
if (l > m)
ret = query(rt << 1 | 1, l, r);
else if (r <= m)
ret = query(rt << 1, l, r);
else
{
ret = query(rt << 1, l, m);
ret |= query(rt << 1 | 1, m + 1, r);
}
push_up(rt);
return ret;
}
int arr[MAXN];//即將被離散化的數組
int ori[MAXN];//arr的副本
int uni[MAXN];//去重後的數組,則離散前的值爲uni[x-1]
int discretization(int n)
{
sort(uni, uni + n);
int size = unique(uni, uni + n) - uni;
for (int i = 0; i < n; ++i)
arr[i] = lower_bound(uni, uni + size, arr[i]) - uni + 1;//arr[i]在原來數組中排第幾個,也就是第幾大
return size;
}
int main(void)
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n, T;
scanf("%d", &T);
while (T--)
{
scanf("%d", &n);
for (int i = 0; i < 2 * n; i += 2)
scanf("%d %d", arr + i, arr + i + 1);
memcpy(uni, arr, sizeof(int) * 2 * n);
memcpy(ori, arr, sizeof(int) * 2 * n);
int N = discretization(2 * n);
buildTree(1, 1, N);
int ans = 0;
for (int i = 2 * n - 1; i >= 1; i -= 2)
{
if (query(1, arr[i - 1], arr[i]))
++ans;
}
printf("%d\n", ans);
}
}