【Luogu】P3369 【模板】普通平衡树(树状数组)
P3369 【模板】普通平衡樹(樹狀數組)
一、樹狀數組
樹狀數組(Binary Indexed Tree(B.I.T), Fenwick Tree)是一個查詢和修改復雜度都為log(n)的數據結構。
這張圖總是讓很多初學者望而生畏(好吧只是我)
所以在學習它之前,我們來看看線段樹。
(現在我默認大家都會線段樹)
我們知道如果\(a + b = c\),則\(b = c - a\)。
所以,所有節點的右兒子都是不需要的。
我們把線段樹上不必要的節點去掉。
它長得會像這樣。
這種數據結構我們稱它為樹狀數組。可以發現所有線段的右斷點都互不相同,所以我們把它按右端點重新編號。
可以發現一些性質:
故我們可以寫出給一個數加\(x\)的代碼。即順著邊依次更行它的祖先。
void update(int x, int y) {for (int i = x; i <= n; i += lowbit(i)) c[i] += y; }我們還需要查詢\([l, r]\)的和,即為\([1, r]\)的和 \(-\) \([1, l - 1]\)的和。
下面有一個求\([1, x]\)的和的代碼。
我們再根據樹狀數組的圖可以發現其實就是對x進行二進制拆分。
求出每一段的和。
二、這道題的解釋
我們可以考慮類似計數的方法。即如果\(x\)比較小,我們可以用\(num[x]\)表示\(x\)出現的次數。所以查找排名即為查詢比\(x\)小的數的\(num\)和。
三、Kth()
我們考慮在樹狀數組上進行類似倍增的操作。
int _kth(int k) {int ret = 0, sum = 0;for (int i = 20; i >= 0; --i)if (ret + (1 << i) <= lcnt && sum + c[ret + (1 << i)] < k) {sum += c[ret + (1 << i)];ret += 1 << i;}for (int i = 0; i <= 20; ++i)if (sum + c[ret + (1 << i)] >= k) {ret += 1 << i;break;}return ret; }簡單地說,就是先跳大的,再跳最小一步使剛好大于等于k。
四、代碼
#include <stdio.h> #include <cstring> #include <cstdlib> #include <cmath> #include <iostream> #include <algorithm> using namespace std; const int MAXN = 100005; int n, opt[MAXN], num[MAXN], lcnt, lsh[MAXN]; class BinaryIndexTree {private:int c[MAXN];int _kth(int k) {int ret = 0, sum = 0;for (int i = 20; i >= 0; --i)if (ret + (1 << i) <= lcnt && sum + c[ret + (1 << i)] < k) {sum += c[ret + (1 << i)];ret += 1 << i;}for (int i = 0; i <= 20; ++i)if (sum + c[ret + (1 << i)] >= k) {ret += 1 << i;break;}return ret;}void _insert(int x) {for (int i = x; i <= n; i += i & -i) ++c[i];}void _erase(int x) {for (int i = x; i <= n; i += i & -i) --c[i];}int num(int x) {int ret = 0;for (int i = x; i; i -= i & -i) ret += c[i];return ret;}public:int kth(int k) { return _kth(k); }void insert(int x) { _insert(x); }void erase(int x) { _erase(x); }int rank(int x) { return num(x - 1) + 1; }int pre(int x) { return _kth(num(x - 1)); }int suc(int x) { return _kth(num(x) + 1); } } bitree; int main() {scanf("%d", &n);for (int i = 1; i <= n; ++i) {scanf("%d%d", &opt[i], &num[i]);if (opt[i] != 4) lsh[++lcnt] = num[i];}sort(lsh + 1, lsh + lcnt + 1);lcnt = unique(lsh + 1, lsh + lcnt + 1) - lsh - 1;for (int i = 1; i <= n; ++i) {if (opt[i] == 4) {printf("%d\n", lsh[bitree.kth(num[i])]);} else {int x = lower_bound(lsh + 1, lsh + lcnt + 1, num[i]) - lsh;if (opt[i] == 1) bitree.insert(x);else if (opt[i] == 2) bitree.erase(x);else if (opt[i] == 3) printf("%d\n", bitree.rank(x));else if (opt[i] == 5) printf("%d\n", lsh[bitree.pre(x)]);else if (opt[i] == 6) printf("%d\n", lsh[bitree.suc(x)]); }}return 0; }轉載于:https://www.cnblogs.com/herald/p/9879577.html
總結
以上是生活随笔為你收集整理的【Luogu】P3369 【模板】普通平衡树(树状数组)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 应用在vue项目里的axios使用方法
- 下一篇: Oracle 备份还原