[关闭]
@wsndy-xx 2018-06-25T17:20:58.000000Z 字数 1030 阅读 971

poj 2104 K-th Number

题解

区间第k大
主席树裸题

https://blog.csdn.net/CillyB/article/details/75912440

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. const int N = 1e5 + 10;
  5. int n, m, cnt;
  6. int Root[N], rank[N], Lson[N * 20], Rson[N * 20], W[N * 20];
  7. struct Node {
  8. int x, id;
  9. bool operator <(Node a) const {return x < a.x;}
  10. } data[N];
  11. void Fill(int x, int y) {Lson[x] = Lson[y], Rson[x] = Rson[y], W[x] = W[y];}
  12. void Update(int num, int &rt, int l, int r) {
  13. Fill(++ cnt, rt);
  14. rt = cnt;
  15. W[rt] ++;
  16. if(l == r) return ;
  17. int mid = (l + r) >> 1;
  18. if(num <= mid) Update(num, Lson[rt], l, mid);
  19. else Update(num, Rson[rt], mid + 1, r);
  20. }
  21. int Ans;
  22. void Ask(int i, int j, int k, int l, int r) {
  23. int del = W[Lson[j]] - W[Lson[i]];
  24. if(l == r) {Ans = l; return ;}
  25. int mid = (l + r) >> 1;
  26. if(k <= del) Ask(Lson[i], Lson[j], k, l, mid);
  27. else Ask(Rson[i], Rson[j], k - del, mid + 1, r);
  28. }
  29. int main() {
  30. std:: cin >> n >> m;
  31. for(int i = 1; i <= n; i ++) {std:: cin >> data[i].x; data[i].id = i;}
  32. std:: sort(data + 1, data + n + 1);
  33. for(int i = 1; i <= n; i ++) rank[data[i].id] = i;
  34. for(int i = 1; i <= n; i ++) {
  35. Root[i] = Root[i - 1];
  36. Update(rank[i], Root[i], 1, n);
  37. }
  38. for(int i = 1; i <= m; i ++) {
  39. int l, r, k;
  40. std:: cin >> l >> r >> k;
  41. Ask(Root[l - 1], Root[r], k, 1, n);
  42. std:: cout << data[Ans].x << "\n";
  43. }
  44. return 0;
  45. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注