fork download
  1. def main():
  2. import sys
  3. input = sys.stdin.read
  4. data = input().split()
  5.  
  6. index = 0
  7. t = int(data[index])
  8. index += 1
  9. results = []
  10.  
  11. for _ in range(t):
  12. n = int(data[index])
  13. index += 1
  14. a = list(map(int, data[index:index + n]))
  15. index += n
  16.  
  17. count = 0
  18. diff_count = {} # 用于统计差值出现的次数
  19.  
  20. for i in range(n):
  21. # 计算当前元素与位置(i+1)的差值
  22. # 原题中i,j是数学上的1-based索引,所以这里用i+1
  23. curr_diff = a[i] - (i + 1)
  24.  
  25. # 之前已经有多个相同差值的元素,每个都能与当前元素形成有效对
  26. if curr_diff in diff_count:
  27. count += diff_count[curr_diff]
  28.  
  29. # 更新当前差值的出现次数(放在后面处理,确保i<j的顺序)
  30. diff_count[curr_diff] = diff_count.get(curr_diff, 0) + 1
  31.  
  32. results.append(str(count))
  33.  
  34. sys.stdout.write("\n".join(results) + "\n")
  35.  
  36. if __name__ == "__main__":
  37. main()
Success #stdin #stdout 0.01s 7072KB
stdin
4
6
3 5 1 4 6 6
3
1 2 3
4
1 3 3 4
6
1 6 3 4 5 6
stdout
1
3
3
10