Problem Author: | Tamzid Alahi (Tamzid1) and Hasan Saleh (MathModel) |
Prepared by: | Hasan Saleh (MathModel) |
Edited by: | Hasan Saleh (MathModel) |
Solution
For each index , define the class key
We want to maximize the number of pairs with K_i=K_j, while we may apply at most one operation a_x\leftarrow a_x+1 for a single .
1) Baseline (no operation). Let be the frequency of value among \{K_i\}. The number of valid pairs is
2) Try one increment at . If we increase a_i, its key becomes
while all other K_j stay the same. The pair contribution of index changes from \text{cnt}[K_i]-1 to
because we conceptually remove from \text{cnt}[K_i] first, then add it to the class of K_i'. Hence the new total is
We simply take
Constraints give a_i\le 10^5, so a_i+1\le 10^5+1. Precompute for all 1\le x\le 100001 once using a linear/prime-sieve style totient sieve.
Complexity \mathcal{O}(10^5 \log \log 10^5+\sum n)
import math
M=100001
phi=list(range(M+1))
for p in range(2,M+1):
if phi[p]==p:
for x in range(p,M+1,p):
phi[x]-=phi[x]//p
def lcm(a,b):
return a//math.gcd(a,b)*b
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
K=[lcm(i+1, phi[a[i]]) for i in range(n)]
from collections import Counter
cnt=Counter(K)
base=sum(c*(c-1)//2 for c in cnt.values())
ans=base
for i in range(n):
x=K[i]
y=lcm(i+1, phi[a[i]+1])
cx=cnt[x]
cy=cnt.get(y,0)
if y==x:
cur=base
else:
cur=base-(cx-1)+cy
if cur>ans: ans=cur
print(ans)