美文网首页
(树状数组) AcWing 241. 楼兰图腾

(树状数组) AcWing 241. 楼兰图腾

作者: 来到了没有知识的荒原 | 来源:发表于2021-03-15 16:38 被阅读0次

    AcWing 241. 楼兰图腾

    树状数组

    #include<bits/stdc++.h>
    
    using namespace std;
    typedef long long LL;
    const int N = 2000010;
    int n;
    int a[N], tr[N];
    int Lower[N], Greater[N];
    
    
    int lowbit(int x) {
        return x & -x;
    }
    
    void add(int x, int v) {
        for (int i = x; i < N; i += lowbit(i))tr[i] += v;
    }
    
    int get(int x) {
        int res = 0;
        for (int i = x; i; i -= lowbit(i))res += tr[i];
        return res;
    }
    
    int main() {
        cin >> n;
        for (int i = 1; i <= n; i++)cin >> a[i];
    
        for (int i = 1; i <= n; i++) {
            int y = a[i];
            Lower[i] = get(y - 1);
            Greater[i] = get(n) - get(y);
            add(y, 1);
        }
    
        memset(tr, 0, sizeof tr);
        LL res1 = 0, res2 = 0;
        for (int i = n; i >= 1; i--) {
            int y = a[i];
            res1 += Greater[i] * 1ll * (get(n) - get(y));
            res2 += Lower[i] * 1ll * get(y - 1);
            add(y, 1);
        }
    
        cout << res1 << " " << res2;
    
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:(树状数组) AcWing 241. 楼兰图腾

          本文链接:https://www.haomeiwen.com/subject/azvkcltx.html