Java教程

树状数组

本文主要是介绍树状数组,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录
  • 单点修改 + 单点查询
    • 楼兰图腾

单点修改 + 单点查询

楼兰图腾

题目描述
image
image
参考题解

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

const int N = 2e5+5;

typedef long long LL;

int n;
int a[N];
int treeMessage[N]; //the cnt of i

int ll[N], lg[N], rl[N], rg[N];

int lowbit(int x)
{
    return x & (-x);
}

void add(int x, int v)
{
    for(; x <= n; x += lowbit(x))
    {
        treeMessage[x] += v;
    }
}

// the sum of treeMessage[i], i: 1~x
int query(int x)
{
    int ans = 0;
    while(x > 0)
    {
        ans += treeMessage[x];
        x = x - lowbit(x);
    }
    return ans;
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; ++ i)
    {
        scanf("%d", a+i);
    }
    for(int i = 1; i <= n; i ++)
    {
        ll[i] = query(a[i]-1);
        lg[i] = i-1 - query(a[i]); //之前有i-1个数,不包括a[i]
        add(a[i], 1);
    }
    memset(treeMessage, 0, sizeof treeMessage);
    for(int i = n; i > 0; -- i)
    {
        rl[i] = query(a[i]-1);
        rg[i] = n-i - query(a[i]);
        add(a[i], 1);
    }
    LL ans1 = 0, ans2 = 0;
    for(int i = 1; i <= n; ++ i)
    {
        ans1 += lg[i] * (LL)rg[i];
        ans2 += ll[i] * (LL)rl[i];
    }
    cout << ans1 << " " << ans2 << endl;
    return 0;
}
这篇关于树状数组的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!