hdu 2838 树状数组

思路:从后面往前面插,用一个二维树状数组保存,c[i][0]表示比i小的元素和,c[i][1]表示比i小的元素个数。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#define Maxn 100010
#define lowbit(x) (x&(-x))
using namespace std;
__int64 C[Maxn][2],n,num[Maxn],cnt;
__int64 Sum(__int64 pos)
{
    __int64 sum=0;
    while(pos)
    {
        sum+=C[pos][0];
        cnt+=C[pos][1];
        pos-=lowbit(pos);
    }
    return sum;
}
void update(__int64 pos)
{
    __int64 val=pos;
    while(pos<=n)
    {
        C[pos][0]+=val;
        C[pos][1]++;
        pos+=lowbit(pos);
    }
}
int main()
{
    int i,j;
    while(scanf("%I64d",&n)!=EOF)
    {
        memset(C,0,sizeof(C));
        for(i=1;i<=n;i++)
            scanf("%I64d",num+i);
        __int64 ans=0;
        for(i=n;i>=1;i--)
        {
            cnt=0;
            ans+=Sum(num[i]);
            ans+=num[i]*cnt;
            update(num[i]);
        }
        printf("%I64d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wangfang20/p/3227143.html