盒子
盒子
文章目录
  1. 题目
  2. 题意
  3. 思路
  4. 代码

POJ2104 K-th Number(静态区间第K大 主席树)

题目

源地址:http://poj.org/problem?id=2104

题意

静态查询区间第K大数

思路

http://www.cnblogs.com/Empress/p/4652449.html
主席数利用函数式线段树来维护数列,即每一个前缀维护一个线段树。再利用两个相邻的线段树只需要修改log级别,所以空间也能开下。一般用来解决区间第k大问题

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#define pb push_back
#define INF 1 << 30
#define fi first
#define se second
#define debug puts("=====================");
using namespace std;
typedef long long ll;
#define lson l, m
#define rson m + 1, r
const int N = 1e5 + 5;
int ln[N << 5], rn[N << 5], sum[N << 5];
int tot;
int a[N], root[N], b[N];
int build(int l, int r) {
int rt = ++tot;
sum[rt] = 0;
if (l < r) {
int m = l + r >> 1;
ln[rt] = build(lson);
rn[rt] = build(rson);
}
return rt;
}
int update(int pre, int l, int r, int x) {
int rt = ++tot;
ln[rt] = ln[pre], rn[rt] = rn[pre], sum[rt] = sum[pre] + 1;
if (l < r) {
int m = l + r >> 1;
if (x <= m) ln[rt] = update(ln[pre], lson, x);
else rn[rt] = update(rn[pre], rson, x);
}
return rt;
}
int query(int u, int v, int l, int r, int k) {
if (l >= r) return l;
int m = l + r >> 1;
int num = sum[ln[v]] - sum[ln[u]];
if (num >= k) return query(ln[u], ln[v], lson, k);
else return query(rn[u], rn[v], rson, k - num);
}
int main () {
tot = 0;
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", a + i), b[i] = a[i];
sort(b + 1, b + n + 1);
int cnt = unique(b + 1, b + n + 1) - b - 1;
root[0] = build(1, cnt);
for (int i = 1; i <= n; i++) {
int x = lower_bound(b + 1, b + n + 1, a[i]) - b;
root[i] = update(root[i - 1], 1, cnt, x);
}
while(m--) {
int l, r, k;
scanf("%d%d%d", &l, &r, &k);
int x = query(root[l - 1], root[r], 1, cnt, k);
printf("%d\n", b[x]);
}
return 0;
}