首页 > 代码库 > POJ 2104 归并树

POJ 2104 归并树

链接:

http://poj.org/problem?id=2104

代码:

31 int a[MAXN], num[MAXN];
32 VI tree[MAXN << 2];
33 
34 void pushup(int l, int r, int rt) {
35     tree[rt].resize(r - l + 1);
36     merge(all(tree[rt << 1]), all(tree[rt << 1 | 1]), tree[rt].begin());
37 }
38 
39 void build(int l, int r, int rt) {
40     if (l == r) {
41         tree[rt].pb(a[l]);
42         return;
43     }
44     int m = (l + r) >> 1;
45     build(lson);
46     build(rson);
47     pushup(l, r, rt);
48 }
49 
50 int query(int L, int R, int x, int l, int r, int rt) {
51     if (R < l || r < L) return 0;
52     if (L <= l && r <= R) return upper_bound(all(tree[rt]), x) - tree[rt].begin();
53     int m = (l + r) >> 1;
54     return query(L, R, x, lson) + query(L, R, x, rson);
55 }
56 
57 int main() {
58     int n, m;
59     cin >> n >> m;
60     rep(i, 1, n + 1) scanf("%d", a + i), num[i] = a[i];
61     sort(num + 1, num + 1 + n);
62     build(1, n, 1);
63     while (m--) {
64         int i, j, k;
65         scanf("%d%d%d", &i, &j, &k);
66         int lb = 0, ub = n;
67         while (ub - lb > 1) {
68             int mid = (lb + ub) >> 1;
69             int c = query(i, j, num[mid], 1, n, 1);
70             if (c >= k) ub = mid;
71             else lb = mid;
72         }
73         printf("%d\n", num[ub]);
74     }
75     return 0;
76 }

 

POJ 2104 归并树