zoukankan      html  css  js  c++  java
  • LintCode "Interval Sum II"

    Regular segment tree usage. Should be medium though.

    struct Node
    {
        Node(int rs, int re) : s(rs), e(re), left(nullptr), right(nullptr){}    
        int s;
        int e;
        long long sum;
        Node *left;
        Node *right;
    };
    
    class Solution {
        Node *root;
    public:
        
        /**
         * @param A: An integer vector
         */
        Node * _build(int s, int e, vector<int> &A)
        {
        if(s > e) return nullptr;
        Node *p = new Node(s, e);
        if(s == e)
        {
            p->sum = A[s];
            return p;
        }
        int mid = (s + e) / 2;
        p->left = _build(s, mid, A);
        p->right= _build(mid+1, e, A);
        p->sum = p->left->sum + p->right->sum;
        
        return p;
        }
        Solution(vector<int> A) {
            root = _build(0, A.size() - 1, A);
        }
        
        /**
         * @param start, end: Indices
         * @return: The sum from start to end
         */
        long long _query(Node *p, int start, int end)
        {
        if(start == p->s && end == p->e)
        {
            return p->sum;
        }
        
        int mid = (p->s + p->e) / 2;
        if(end <= mid)
        {
            return _query(p->left, start, end);
        }
        else if(start > mid)
        {
            return _query(p->right, start, end);        
        }
        
        long long rl = _query(p->left, start, mid);
        long long rr = _query(p->right,mid+1, end);
        return rl + rr;
        }
        long long query(int start, int end) {
            return _query(root, start, end);
        }
        
        /**
         * @param index, value: modify A[index] to value.
         */
        int _modify(Node *p, int i, int val)
        {
        if(p->s == p->e && i == p->s)
        {
            int d = val - p->sum;
            p->sum = val;
            return d;
        }
        
        int mid = (p->s + p->e) / 2;
        int d = 0;
        if (i <= mid)
        {
            d = _modify(p->left, i, val);
        }
        else
        {
            d = _modify(p->right,i, val);
        }
        p->sum += d;
        return d;
        }
        void modify(int index, int value) {
            _modify(root, index, value);
        }
    };
    View Code
  • 相关阅读:
    [CF1166E] The LCMs Must be Large
    AtCoder Beginner Contest 161
    [CF1168B] Good Triple
    [CF1172B] Nauuo and Circle
    [CF1185E] Polycarp and Snakes
    [CF1187E] Tree Painting
    Codeforces Round #631 (Div. 2)
    [CF1200E] Compress Words
    Thinkphp绕过宝塔getshell
    如何成为一个漏洞赏金猎人
  • 原文地址:https://www.cnblogs.com/tonix/p/4894788.html
Copyright © 2011-2022 走看看