传送门:HDU 5147
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.1≤a<b<c<d≤n
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
题意:
给你n个数,要你在这n个数中选出4个数,这四个数满足三个条件:
1.1≤a<b<c<d≤n
2. Aa<Ab
3. Ac<Ad
问你可以选出几个。
题解:
用一个数组存第i个数前有几个数比他小,另个数组存第i个数以后的数可以组成几对数满足ai<aj(用树状数组和后缀和实现);
然后从前往后遍历一遍,两数组相乘即可。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=55000;
int t,n;
ll sum[N],c[N],sumh[N],a[N];
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int k)
{
while(x<=n)
{
c[x]+=k;
x+=lowbit(x);
}
}
ll getsum(int x)
{
ll ans=0;
for(int i=x;i>0;i-=lowbit(i))
{
ans+=c[i];
}
return ans;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(sumh,0,sizeof(sumh));//后n-i个可以组成几对
memset(sum,0,sizeof(sum));//sum存比第i个数小的数有几个
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
scanf("%I64d",&a[i]);
sum[i]=getsum(a[i]);
update(a[i],1);
}
/*for(int i=1;i<=n;i++)
{
printf("%I64d%c",sum[i],i==n?'\n':' ');
}*/
memset(c,0,sizeof(c));
int tot=0;
for(int i=n;i>0;i--)
{
sumh[i]=tot-getsum(a[i]);//计算后面比第i个大的有几个
tot++;
update(a[i],1);
}
for(int i=n;i>0;i--)
{
sumh[i]+=sumh[i+1];
}
ll num=0;
for(int i=2;i<=n-2;i++)
{
num+=sum[i]*(sumh[i+1]);
}
printf("%I64d\n",num);
}
return 0;
}