D. Same Differences
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.
Input
The first line contains one integer t (1≤t≤104). Then tt 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 nn 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.
思路:
我们对原式进行移项可得,要求 ai - i = aj - j 的 对数, 这可以利用哈希,映射法来求解这个问题。为什么我可以通过先加cnt[a[i]-i] 再, cnt[a[i]-i]++, 得到答案呢, 比如a[i]-i 等于 9 的一共有 9个,然后我们要从其中取两个, 那不就是排列组合的C92, 嘛 就是 Cn2, 0+1+2+3+.....n-1 ,因此可以使用我代码中的方法来求解;
代码实现:
#include<bits/stdc++.h>
using namespace std;
void solve()
{
int n;
cin>>n;
vector<int> a(n+1);
long long ans=0;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
map<int,int> cnt;
for(int i=1;i<=n;i++)
{
ans+=cnt[a[i]-i];
cnt[a[i]-i]++;
}
cout<<ans<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
}