K-th Number
之前学主席树写了一遍
最近再看CDQ分治和整体二分,一直不是很理解,看着别人代码稍微理解了一些
1 //比主席树慢了挺多 2 #include <iostream> 3 #include <cstring> 4 #include <cstdio> 5 6 using namespace std; 7 8 const int maxn = 1e5 + 10; 9 const int maxq = 5010; 10 const int inf = 0x3f3f3f3f; 11 12 struct Qry{ 13 int x, y, k; 14 int id, type; 15 Qry(int x = 0, int y = 0, int k = 0, int id = 0, int type = 0): 16 x(x), y(y), k(k), id(id), type(type){} 17 }q[maxn + maxq], q1[maxn + maxq], q2[maxn + maxq]; 18 19 struct Bit{ 20 int n; 21 int a[maxn]; 22 void init(int _n){ 23 n = _n; 24 memset(a, 0, sizeof a); 25 } 26 void add(int i, int x){ 27 for(; i <= n; i += i & -i) a[i] += x; 28 } 29 int sum(int i){ 30 int res = 0; 31 for(; i; i -= i & -i) res += a[i]; 32 return res; 33 } 34 }bit; 35 36 int n, m, a[maxn]; 37 int ans[maxq]; 38 39 void solve(int L, int R, int l, int r){ 40 if(L > R) return; 41 if(l == r){ 42 for(int i = L; i <= R; i++){ 43 if(q[i].type == 2) ans[q[i].id] = l; 44 } 45 return; 46 } 47 int m = l + r >> 1; 48 int f = 0, g = 0; 49 for(int i = L; i <= R; i++){ 50 if(q[i].type == 1){ 51 if(q[i].x <= m) { 52 bit.add(q[i].id, 1); 53 q1[f++] = q[i]; 54 }else q2[g++] = q[i]; 55 }else{ 56 int temp = bit.sum(q[i].y) - bit.sum(q[i].x - 1); 57 if(temp >= q[i].k) { 58 q1[f++] = q[i]; 59 }else{ 60 q[i].k -= temp; 61 q2[g++] = q[i]; 62 } 63 } 64 } 65 for(int i = 0; i < f; i++) if(q1[i].type == 1) bit.add(q1[i].id, -1); 66 memcpy(q + L, q1, f * sizeof(Qry)); 67 memcpy(q + L + f, q2, g * sizeof(Qry)); 68 solve(L, L + f - 1, l, m); 69 solve(L + f, R, m + 1, r); 70 } 71 int main(){ 72 ios::sync_with_stdio(0); 73 while(cin>>n>>m){ 74 bit.init(n); 75 int idx = 0; 76 for(int i = 1; i <= n; i++){ 77 cin>>a[i]; 78 q[++idx] = Qry(a[i], 0, 0, i, 1); 79 } 80 for(int i = 1; i <= m; i++){ 81 int x, y, k; 82 cin>>x>>y>>k; 83 q[++idx] = Qry(x, y, k, i, 2); 84 } 85 solve(1, idx, -inf, inf); 86 for(int i = 1; i <= m; i++){ 87 cout<<ans[i]<<endl; 88 } 89 } 90 }