首页 > 试题广场 >

谐距下标对

[编程题]谐距下标对
  • 热度指数:6003 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
\hspace{15pt}给定一个长度为 n 的整数数组 \{a_1,a_2,\dots,a_n\}。若下标满足 i<ja_j-a_i = j-i,则称 (i,j) 为一对谐距下标对

\hspace{15pt}请计算数组中的谐距下标对数量。

输入描述:
\hspace{15pt}第一行输入整数 n\left(1\leqq n\leqq 10^5\right)
\hspace{15pt}第二行输入 n 个整数 a_1,a_2,\dots,a_n\left(1\leqq a_i\leqq 10^5\right)


输出描述:
\hspace{15pt}输出一个整数,表示谐距下标对数量。
示例1

输入

6
1 2 3 4 5 6

输出

15
from collections import Counter

n = int(input())
numbers = list(map(int, input().split()))

b = [numbers[i] - (i+1) for i in range(n)]
counter = Counter(b)
count = 0
for freq in counter.values():
    if freq >1:
        count += freq*(freq - 1) //2
print(count)


发表于 2025-10-25 23:44:22 回复(0)
import sys

for line in sys.stdin:
    a = line.split()
an=list(map(int,a))

vdict={}
counts=0
for i in range(len(an)):
    v=an[i]-i
    if v not in vdict:
        vdict[v]=1
    else:
        counts+=vdict[v]
        vdict[v]+=1
print(counts)
发表于 2025-09-14 21:20:16 回复(0)
n = int(input())
a = list(map(int,input().split()))

for i in range(n):
    a[i] = a[i]-i
dic = {}
count = 0
for i in range(n):
    if a[i] not in dic.keys():
        dic[a[i]] = 1
    else:
        count += dic[a[i]]
        dic[a[i]] += 1
       
print(count)
发表于 2025-08-26 15:23:32 回复(0)
n = int(input())
a = list(map(int, input().strip().split()))

# 计算每个元素的"值减下标"
diff = [a[i] - i for i in range(n)]

# 统计相同差值的出现次数
count_map = {}
for val in diff:
    count_map[val] = count_map.get(val, 0) + 1

# 计算谐距下标对数量
pairs = 0
for count in count_map.values():
    # 如果有k个元素有相同的"值减下标",则可以形成C(k,2)对
    if count > 1:
        pairs += count * (count - 1) // 2

print(pairs)
发表于 2025-08-22 10:33:14 回复(0)