import java.util.*;
// 类名必须为 Main,符合题目要求
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 读取数组长度n,用int即可(题目约束n≤1e5,未超出int范围)
int n = in.nextInt();
// 1. Map的键(ai - i)改为Long,值(频次)也改为Long(避免频次累计溢出)
Map<Long, Long> countMap = new HashMap<>();
for (int i = 0; i < n; i++) {
int ai = in.nextInt(); // ai≤1e5,用int安全,后续转换为Long计算
// 2. 计算特征值key:强制转换ai为Long,避免ai - i溢出
Long key = (long) ai - i;
// 3. 频次累计:用Long存储频次,getOrDefault默认值0L(Long类型)
countMap.put(key, countMap.getOrDefault(key, 0L) + 1L);
}
// 4. 结果变量count改为Long,确保累加过程不溢出
Long count = 0L;
// 5. 遍历Map的值(Long类型频次),计算组合数
for (Long freq : countMap.values()) {
// 组合数公式:freq*(freq-1)/2,所有操作数均为Long,避免溢出
count += freq * (freq - 1) / 2;
}
// 输出结果(Long类型可直接打印)
System.out.println(count);
}
} 第一次没通过的原因是计数变量c没有改成long long ,使用int造成了数据溢出。
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
int n;
cin>>n;
long long c=0;
unordered_map<int , int> mp;
for (int i=1; i<=n; i++) {
int a;
cin>>a;
mp[a-i]++;
}
for(auto a:mp){
int n=a.second;
if(n>=2){
c+=n*(n-1)/2;
}
}
cout<<c;
}
// 64 位输出请用 printf("%lld")