You are given an array a of n integers. Count the number of pairs of indices (i,j) such that i<j and aj−ai=j−i.
Input
The first line contains one integer t (1≤t≤104). Then t test cases follow.
The first line of each test case contains one integer n (1≤n≤2⋅105).
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤n) — array a.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅105.
Output
For each test case output the number of pairs of indices (i,j) such that i<j and aj−ai=j−i.
Example
Input
4
6
3 5 1 4 6 6
3
1 2 3
4
1 3 3 4
6
1 6 3 4 5 6
Output
1
3
3
10
题意:
给你一组数据,求满足i<j且aj−ai=j−i条件的总数
思路:
a[j]-a[i]=j-i
i-a[i]=j-a[j]
所以当i-a[i]
相等时,他们之间就可以组合为一对,统计每一个i-a[i]
出现的次数,定义i-a[i]
出现的次数为t,因为i<j,所以最后结果就是
t *( t - 1 )/ 2
当记录i-a[i]
出现的次数时,因为i-a[i]
可能为负数,book数组的下标不能为负数,而map容器可以,所以在这里用map容器记录i-a[i]
出现的次数
代码:
#include<stdio.h>
#include<map>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 200010
long long a[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
long long n;
map<long long,long long>mp;
scanf("%lld",&n);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
mp[i-a[i]]++;
}
long long ans=0;
for(int i=-n;i<=n;i++)
{
if(mp[i]>1)
{
ans+=((mp[i])*(mp[i]-1))/2;
}
}
printf("%lld\n",ans);
}
return 0;
}