F. Yet Another Problem About Pairs Satisfying an Inequality
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an array a1,a2,…ana1,a2,…an. Count the number of pairs of indices 1≤i,j≤n1≤i,j≤n such that ai<i<aj<jai<i<aj<j.
Input
The first line contains an integer tt (1≤t≤10001≤t≤1000) — the number of test cases.
The first line of each test case contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the array.
The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109) — the elements of the array.
It is guaranteed that the sum of nn across all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, output a single integer — the number of pairs of indices satisfying the condition in the statement.
Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).
Example
input
Copy
5 8 1 1 2 3 8 2 1 4 2 1 2 10 0 2 1 6 3 4 1 2 8 3 2 1 1000000000 3 0 1000000000 2
output
Copy
3 0 10 0 1
Note
For the first test cases the pairs are (i,j)(i,j) = {(2,4),(2,8),(3,8)}{(2,4),(2,8),(3,8)}.
- The pair (2,4)(2,4) is true because a2=1a2=1, a4=3a4=3 and 1<2<3<41<2<3<4.
- The pair (2,8)(2,8) is true because a2=1a2=1, a8=4a8=4 and 1<2<4<81<2<4<8.
- The pair (3,8)(3,8) is true because a3=2a3=2, a8=4a8=4 and 2<3<4<82<3<4<8.
后悔没有直接跳过来写,这题就是脑筋急转弯
题意就是找到数组里符合ai<i<aj<j的对数。
实际上ai<i和aj<j是一回事等价于ai<i,那么我们只要找到,在aj前满足ai<i的数量就行,考虑到时间复杂度,使用前缀和就行了。
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
const int manx = 2e6 + 10;
long long a[manx];
long long b[manx];
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
long long ans = 0;//开long long 不然爆炸
for (int i = 1; i <= n; i++)
{
cin >> a[i];
b[i] = b[i - 1] + (a[i] < i);//如果满足a[i]<i那么就前缀和就加1
if (a[i] < i && a[i] - 1 >= 1)//判断同时防止越界
{
ans += b[a[i] - 1];//从1开始到a[i]满足的对数,b[i]数组是满足对数的前缀和。
}
}
cout << ans << endl;
}
}