Sequence II
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1004 Accepted Submission(s): 410
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
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
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
题意:在给定序列里面求子序列的个数,子序列满足A1<A2,A3<A4 四个数的顺序要满足原序列里的顺序
思路:很容易想到用数组数组维护前缀和,可是如何找到当前点后面有多少个点对满足(Ai,Aj)(Ai<Aj)呢?
我们可以逆序插入序列里的数据,这样可以求得i点后面有几个点比a[i]小,再用i点后面的点的个数减去可以得到i点后面有几个点比a[i]大,那么以i点为点对的第一个点,是不是就有sum[i]个点对呢? 那么我们只需要维护后缀和,然后每次遍历到i,用qian[i](i点前面比a[i]小的数的个数)乘以hou[i+1](i点后面的满足条件的点对)即可
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define N 50050
int a[N],n;
int c[N];
long long qian[N],hou[N];
int lowbit(int x)
{
return x&-x;
}
void add(int x,int v)
{
for(int i=x;i<=n;i+=lowbit(i))
c[i]+=v;
}
int sum(int x)
{
int ans=0;
for(int i=x;i;i-=lowbit(i))
ans+=c[i];
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
qian[i]=sum(a[i]);
add(a[i],1);
}
memset(c,0,sizeof(c));
for(int i=n;i>=1;i--)
{
hou[i]=n-i-sum(a[i]);
add(a[i],1);
}
for(int i=n-1;i>=1;i--)
hou[i]=hou[i]+hou[i+1];
long long ans=0;
for(int i=1;i<n;i++)
ans+=qian[i]*hou[i+1];
printf("%lld\n",ans);
}
return 0;
}