hdu 5147 Sequence II 树状数组

Sequence II

Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


Problem Description
Long long ago, there is a sequence A with length n. All numbers in this sequence is no smaller than 1 and no bigger than n, and all numbers are different in this sequence.
Please calculate how many quad (a,b,c,d) satisfy:
1. 1a<b<c<dn
2. Aa<Ab
3. Ac<Ad
 
Input
The first line contains a single integer T, indicating the number of test cases.
Each test case begins with a line contains an integer n.
The next line follows n integers A1,A2,,An.

[Technical Specification]
1 <= T <= 100
1 <= n <= 50000
1 <= Ai <= n
 
Output
For each case output one line contains a integer,the number of quad.
 
Sample Input
1 5 1 3 2 4 5
 
Sample Output
4
 
Source
思路:用树状数组求逆序对;
   pre[i]存前边比a[i]小的;
   nex[i]存a[i]开始的二元组;
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pi (4*atan(1.0))
const int N=5e4+10,M=1e6+1010,inf=1e9+10,mod=1e9+7;
const ll INF=1e18+10;
int tree[N];
int a[N];
int pre[N];
int nex[N];
void init()
{
    memset(tree,0,sizeof(tree));
    memset(pre,0,sizeof(pre));
    memset(nex,0,sizeof(nex));
}
int lowbit(int x)
{
    return x&(-x);
}
void update(int x,int c)
{
    while(x<N)
    {
        tree[x]=tree[x]+c;
        x+=lowbit(x);
    }
}
int query(int x)
{
    int sum=0;
    while(x)
    {
        sum+=tree[x];
        x-=lowbit(x);
    }
    return sum;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        init();
        int n;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
        for(int i=1;i<=n;i++)
        {
            pre[i]=query(a[i]-1);
            update(a[i],1);
        }
        memset(tree,0,sizeof(tree));
        for(int i=n;i>=1;i--)
        {
            nex[i]=query(n)-query(a[i])+nex[i+1];
            update(a[i],1);
        }
        ll ans=0;
        for(int i=1;i<=n;i++)
            ans+=(ll)pre[i]*nex[i+1];
        printf("%lld
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jhz033/p/5896624.html