D. Zigzags
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a1,a2…an. Calculate the number of tuples (i,j,k,l) such that:
1≤i<j<k<l≤n;
ai=ak and aj=al;
Input
The first line contains a single integer t (1≤t≤100) — the number of test cases.
The first line of each test case contains a single integer n (4≤n≤3000) — the size of the array a.
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤n) — the array a.
It’s guaranteed that the sum of n in one test doesn’t exceed 3000.
Output
For each test case, print the number of described tuples.
Example
input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
output
5
2
Note
In the first test case, for any four indices i<j<k<l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
(1,2,4,6): a1=a4 and a2=a6;
(1,3,4,6): a1=a4 and a3=a6.
参考资料:CodeForces 1400 D-Zigzags 枚举+思维+前缀维护
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=3e3+10;
ll pre[N][N];
//pre[pos][num],来维护pos位置前的数值等于num的位置有多少个。
//这样就可以在O(n^2)的枚举的同时,完成答案的更新
int ai[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
memset(pre,0,sizeof pre);
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&ai[i]);
for(int i=2;i<=n+1;i++){
for(int j=i-1;j>=1;j--){
pre[i][ai[j]]++;
}
}
ll ans=0;
//(i,j,k,l)
for(int j=2;j<n-1;j++){
for(int k=j+1;k<n;k++){
ll num1=pre[j][ai[k]];
ll num2=pre[n+1][ai[j]]-pre[k][ai[j]];
if(ai[k]==ai[j]) num2--;
ans+=num1*num2;
}
}
printf("%lld\n",ans);
}
return 0;
}
想法:(i,j,k,l)中ai=ak,aj=al,遍历j,k找到k前的j(i可以在前缀出来的数目中任取一),和j后的k(j可以在前缀后差值的数目任取一),乘起来就是解