poj2104 主席樹 區間K大 線上 無修改

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   io   資料   

關於主席樹:

主席樹(Chairman Tree)是一種離線資料結構,使用函數式線段樹維護每一時刻離散之後的數字出現的次數,由於各曆史版本的線段樹結構一致,可以相減得出區間資訊,即該區間內出現的數字和對應的數量,由於線上段樹內,左子樹代表的數字都小與右子樹,便可像平衡樹一樣進行K大詢問。建立一顆樹是\(O(logn)\),查詢一次也為\(O(logn)\)。

比劃分樹好想&寫多了,但是在POJ上比劃分樹慢一些。

CODE:
 1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 const int maxn = 100000 + 100; 5  6 int id[maxn], root[maxn], a[maxn], b[maxn], n, m, size; 7 struct chairman_tree_node { 8     int ls, rs, w; 9 } T[maxn * 23];10 void insert(int l, int r, int &pos, int val) {11     T[++size] = T[pos], pos = size;12     ++T[pos].w;13     if(l == r) return ;14     int mid = (l + r) >> 1;15     if(val <= mid) insert(l, mid, T[pos].ls, val);16     else insert(mid + 1, r, T[pos].rs, val);17 }18 int query(int p, int q, int l, int r, int k) {19     if(l == r) return l;20     int t = T[T[q].ls].w - T[T[p].ls].w;21     int mid = (l + r) >> 1;22     if(k <= t) return query(T[p].ls, T[q].ls, l, mid, k);23     else return query(T[p].rs, T[q].rs, mid + 1, r, k - t);24 }25 bool cmp(int x, int y) {26     return a[x] < a[y];27 }28 int main() {29     scanf("%d%d", &n, &m);30     for(int i = 1; i <= n; ++i) {31         scanf("%d", &a[i]);32         id[i] = i;33     }34     sort(id + 1, id + n + 1, cmp);35     for(int i = 1; i <= n; ++i) {36         b[id[i]] = i;37     }38     for(int i = 1; i <= n; ++i) {39         root[i] = root[i - 1];40         insert(1, n, root[i], b[i]);41     }42     for(int i = 1; i <= m; ++i) {43         int l, r, k;44         scanf("%d%d%d", &l, &r, &k);45         printf("%d\n", a[id[query(root[l - 1], root[r], 1, n, k)]]);46     }47     return 0;48 }
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.