题意:找到有序对(A, B, C, D){1=< A < B < C < D <= N}使得数组P[A] < P[C] && P[C] < P[D]
做法:
暴搜每一个数组中P[i]>P[j] 的有序对(I,J)存入 DP[][]数组中,其中DP[I][J]表示从1到J大于P[I]的数的个数或者是从I到J大于P[I]的数的个数,answer = answer + dp[c][b - 1]*(dp[b][n] - dp[b][c]);
枚举所有的B, C相加就是answer
//AC 代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e3 + 10;
int p[maxn];
int station[maxn];
ll dp[maxn][maxn];
void init(int n){
for(int i = 0; i <= n; i++){
for(int j = 0;j <= n; j++){
dp[i][j] = 0;
}
}
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
init(n);
for(int i = 1;i <= n; i++){
cin>>p[i];
station[p[i]] = i;
}
for(int i = 1;i <= n; i++){
for(int j = 1;j <= i - 1; j++){
if(p[i] > p[j]){
dp[i][j] = dp[i][j - 1] + 1;
}else{
dp[i][j] = dp[i][j - 1];
}
}
for(int j = i + 1; j <= n; j++){
if(p[i] > p[j]){
dp[i][j] = dp[i][j - 1] + 1;
}else{
dp[i][j] = dp[i][j - 1];
}
}
}
ll ans = 0;
for(int b = 2; b <= n - 1; b++){
for(int c = b + 1; c <= n - 1; c++){
ans = ans + dp[c][b - 1]*(dp[b][n] - dp[b][c]);
}
}
cout<<ans<<endl;
}
return 0;
}