其他分享
首页 > 其他分享> > acwing 241. 楼兰图腾(树状数组)

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

作者:互联网

题意

在这里插入图片描述

思路

  1. 树状数组,我们通过枚举顺序进行插入,然后对树状数组进行区间查询可以了。

代码

#include <bits/stdc++.h>
using namespace std;

#define ll long long
const int N = 200005;
int n, a[N], c[N], great[N], lower[N];

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

void insert(int x, int y)
{
    while (x <= n)
    {
        c[x] += y;
        x += lowbit(x);
    }
}

int sum(int x)
{
    int all = 0;
    while (x > 0)
    {
        all += c[x];
        x -= lowbit(x);
    }
    return all;
}


int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++) scanf("%d", &a[i]);

    for (int i = 1; i <= n; i ++) {
        great[i] = sum(n) - sum(a[i]);
        lower[i] = sum(a[i] - 1);
        insert(a[i], 1);
    }

    memset(c, 0, sizeof c);
    ll res1 = 0, res2 = 0;
    for (int i = n; i; i --) {
        res1 += 1LL * great[i] * (sum(n) - sum(a[i]));
        res2 += 1LL * lower[i] * sum(a[i] - 1);
        insert(a[i], 1);
    }

    printf("%lld %lld\n", res1, res2);


    return 0;
}

标签:return,树状,int,lowbit,sum,res1,res2,241,acwing
来源: https://blog.csdn.net/qq_34261446/article/details/121144180