可持久化线段树

struct Node {
    int val;
    Node *ch[2];
};

int a[maxn], n;
Node *root[maxn];

Node* sgtIns(Node* q, int pos) { // 在q的基础上将pos这个位置的数+1, 并返回一个新的线段树的根
    int l = 0, r = n;
    Node *s = new Node, *p = s;
    while (l < r) {
        p->val = q ? q->val + 1 : 1;
        int mid = (l + r)>> 1;
        if (pos <= mid) {
            p->ch[1] = q ? q->ch[1] : 0;
            p = p->ch[0] = new Node;
            q = q ? q->ch[0] : 0;
            r = mid;
        } else {
            p->ch[0] = q ? q->ch[0] : 0;
            p = p->ch[1] = new Node;
            q = q ? q->ch[1] : 0;
            l = mid + 1;
        }
    }
    p->val = q ? q->val + 1 : 1;
    return s;
}
int main() {
    cin >> n;
    for (int i = 1; i <= n; ++ i) {
        cin >> a[i];
    }
    root[0] = 0;
    for (int i = 1; i <= n; ++ i) {
        root[i] = sgtIns(root[i - 1], a[i]);
    }
} 

 

posted @ 2017-01-25 16:14  Mr.9Pounds15Pence  阅读(159)  评论(0编辑  收藏  举报