Title
CodeForces 1400 D. Zigzags
Time Limit
2 seconds
Memory Limit
256 megabytes
Problem Description
You are given an array a 1 , a 2 … a n a_1, a_2 \dots a_n a1,a2…an. Calculate the number of tuples ( i , j , k , l ) (i, j, k, l) (i,j,k,l) such that:
- 1 ≤ i < j < k < l ≤ n 1\le i<j<k<l\le n 1≤i<j<k<l≤n
- a i = a k a_i=a_k ai=akand a j = a l a_j=a_l aj=al;
Input
The first line contains a single integer t t t ( 1 ≤ t ≤ 100 1 \le t \le 100 1≤t≤100) — the number of test cases.
The first line of each test case contains a single integer n n n ( 4 ≤ n ≤ 3000 4 \le n \le 3000 4≤n≤3000) — the size of the array a a a.
The second line of each test case contains n n n integers a 1 , a 2 , … , a n a_1, a_2, \dots, a_n a1,a2,…,an ( 1 ≤ a i ≤ n 1 \le a_i \le n 1≤ai≤n) — the array a a a.
It’s guaranteed that the sum of n n n in one test doesn’t exceed 3000 3000 3000.
Output
For each test case, print the number of described tuples.
Sample Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Sample Onput
5
2
Note
In the first test case, for any four indices i < j < k < l i < j < k < l i<j<k<l are valid, so the answer is the number of tuples.
In the second test case, there are 2 2 2 valid tuples:
Source
题意
给一个长度为n的数组,求满足
- 1 ≤ i < j < k < l ≤ n 1\le i<j<k<l\le n 1≤i<j<k<l≤n
- a i = a k a_i=a_k ai=akand a j = a l a_j=a_l aj=al;
的(i,j,k,l)的四元组个数
思路
一开始想枚举两个位置,用前缀和来快速计算对数,发现只能够 O ( N 3 ) O(N^3) O(N3)。
后来想到使用树状数组去解决,记录所有对数的l,r。
对于l相同的先不插入树状数组,因为l相同的不能互相作为答案。
因为是按顺序加入的对数,所以对子都是排序的。
当l不同时,将上一次相同的l的r全部插入树状数组。
此时树状数组里的l均小于当前l,那么只要求r在(l,r-1)之间即可,相减可得。
复杂度 O ( N 2 l o g N ) O(N^2logN) O(N2logN),带个常数2。
审视自我
赛后看到有
O
(
N
2
)
O(N^2)
O(N2)的做法,即枚举两个位置i,j。做一个i之前的桶,对数不断累加桶[a[j]],贡献到答案即可。
AC代码:
被hack了,忘记判断对子为空时取[0]会越界,请把last初始化为--1
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int maxn = 3e5 + 5;
const ll inf = 0x3f3f3f3f;
const ll mod = 1e9 + 7;
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
class BIT {
public:
vector<ll> tree;
int n;
BIT(int _n) : n(_n), tree(_n + 1, 0) {}
static int lowbit(int x) { return x & (-x); }
ll query(int x) {
ll ans = 0;
while (x) {
ans += tree[x];
x -= lowbit(x);
}
return ans;
}
void add(int x, ll val) {
while (x <= n) {
tree[x] += val;
x += lowbit(x);
}
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
vector<pii> p;
for (int i = 1; i <= n; ++i) {
for (int j = i + 1; j <= n; ++j) {
if (a[i] == a[j]) {
p.emplace_back(i, j);
}
}
}
BIT T(n);
ll ans = 0;
queue<int> q;
for (int i = 0, last = p[0].first; i < p.size(); ++i) {
if (p[i].first != last) {
while (q.size()) {
T.add(q.front(), 1);
q.pop();
}
last = p[i].first;
}
ans += T.query(p[i].second - 1) - T.query(p[i].first);
if (last == p[i].first) q.push(p[i].second);
}
cout << ans << endl;
}
return 0;
}