划分树+二分枚举
http://acm.hdu.edu.cn/showproblem.php?pid=4417
划分树http://www.cnblogs.com/pony1993/archive/2012/07/17/2594544.html
直接搬来模板 打得
View Code
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 #define N 100005 6 int a[N], as[N];//原数组,排序后数组 7 int n, m; 8 int sum[20][N];//记录第i层的1~j划分到左子树的元素个数(包括j) 9 int tree[20][N];//记录第i层元素序列 10 void build(int c, int l, int r){ 11 int i, mid = (l + r) >> 1, lm = mid - l + 1, lp = l, rp = mid + 1; 12 for (i = l; i <= mid; i++){ 13 if (as[i] < as[mid]){ 14 lm--;//先假设左边的(mid - l + 1)个数都等于as[mid],然后把实际上小于as[mid]的减去 15 } 16 } 17 for (i = l; i <= r; i++){ 18 if (i == l){ 19 sum[c][i] = 0;//sum[i]表示[l, i]内有多少个数分到左边,用DP来维护 20 }else{ 21 sum[c][i] = sum[c][i - 1]; 22 } 23 if (tree[c][i] == as[mid]){ 24 if (lm){ 25 lm--; 26 sum[c][i]++; 27 tree[c + 1][lp++] = tree[c][i]; 28 }else 29 tree[c + 1][rp++] = tree[c][i]; 30 } else if (tree[c][i] < as[mid]){ 31 sum[c][i]++; 32 tree[c + 1][lp++] = tree[c][i]; 33 } else{ 34 tree[c + 1][rp++] = tree[c][i]; 35 } 36 } 37 if (l == r)return; 38 build(c + 1, l, mid); 39 build(c + 1, mid + 1, r); 40 } 41 int query(int c, int l, int r, int ql, int qr, int k){ 42 int s;//[l, ql)内将被划分到左子树的元素数目 43 int ss;//[ql, qr]内将被划分到左子树的元素数目 44 int mid = (l + r) >> 1; 45 if (l == r){ 46 return tree[c][l]; 47 } 48 if (l == ql){//这里要特殊处理! 49 s = 0; 50 ss = sum[c][qr]; 51 }else{ 52 s = sum[c][ql - 1]; 53 ss = sum[c][qr] - s; 54 }//假设要在区间[l,r]中查找第k大元素,t为当前节点,lch,rch为左右孩子,left,mid为节点t左边界和中间点。 55 if (k <= ss){//sum[r]-sum[l-1]>=k,查找lch[t],区间对应为[ left+sum[l-1], left+sum[r]-1 ] 56 return query(c + 1, l, mid, l + s, l + s + ss - 1, k); 57 }else{//sum[r]-sum[l-1]<k,查找rch[t],区间对应为[ mid+1+l-left-sum[l-1], mid+1+r-left-sum[r] ] 58 return query(c + 1, mid + 1, r, mid - l + 1 + ql - s, mid - l + 1 + qr - s - ss,k - ss); 59 } 60 } 61 int main() 62 { 63 int i, j, k,t,kk=0; 64 scanf("%d",&t); 65 while(t--) 66 { 67 kk++; 68 scanf("%d%d", &n, &m); 69 for (i = 1; i <= n; i++) 70 { 71 scanf("%d", &a[i]); 72 tree[0][i] = as[i] = a[i]; 73 } 74 sort(as + 1, as + 1 + n); 75 build(0, 1, n); 76 printf("Case %d:\n",kk); 77 while(m--) 78 { 79 scanf("%d%d%d",&i,&j,&k); 80 i++; 81 j++; 82 int low = 1; 83 int high = j-i+1; 84 int re = 0; 85 while(low<=high) 86 { 87 int m = (low+high)>>1; 88 int w = query(0, 1, n, i, j, m); 89 if(w<=k) 90 { 91 low = m+1; 92 re = m; 93 } 94 else 95 high = m-1; 96 } 97 printf("%d\n",re); 98 } 99 } 100 return 0; 101 }