D. Same Differences 题解主要应用cn2公式
题意:输入 t 组数据找到 a[j] - i = a[i] - j 的个数
题解:脑子一转 嗯嗯 直接找每组 a[j] = j 的个数 然后求cn2
最后将每一种 a[j] - j的 cn2 相加
朴素代码:
#include<iostream>
#include<map>
using namespace std;
const int N = 2e5 + 10;
int a[N];
int n, m;
void judge()
{
long long int res = 0;
map<long long int, long long int>mp;
for (int i = 1; i <= n; i++)
mp[a[i] - i]++;
for (map<long long int, long long int>::iterator it = mp.begin(); it != mp.end(); it++)
res += (*it).second * ((*it).second - 1) / 2;
cout << res << endl;
mp.clear();
}
int main()
{
cin >> m;
while (m--)
{
cin >> n;
for (int i = 1; i <= n; i++)cin >> a[i];
judge();
}
return 0;
}
妙了那么一点 求 cn2:
#include<iostream>
#include<map>
using namespace std;
const int N = 2e5 + 10;
int a[N];
int n, m;
void judge()
{
long long int res = 0;
map<int, int>mp;
for (int i = 1; i <= n; i++)
{
if (mp.count(a[i] - i))
res += mp[a[i] - i];//新增的 和 原来的都可以匹配一次
mp[a[i]- i]++;
}
cout << res << endl;
mp.clear();
}
int main()
{
cin >> m;
while (m--)
{
cin >> n;
for (int i = 1; i <= n; i++)cin >> a[i];
judge();
}
return 0;
}