Close Combat#12255

Close Combat (Editorial)

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

K_i=\operatorname{lcm}\big(i,\ \varphi(a_i)\big).

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

\text{pairs}_0=\sum_v \binom{\text{cnt}[v]}{2}.

2) Try one increment at . If we increase a_i, its key becomes

K_i'=\operatorname{lcm}\big(i,\ \varphi(a_i+1)\big),

while all other K_j stay the same. The pair contribution of index changes from \text{cnt}[K_i]-1 to

\text{cnt}'[K_i']= \begin{cases} \text{cnt}[K_i'] & \text{if } K_i'\ne K_i,\\ \text{cnt}[K_i]-1 & \text{if } K_i'=K_i, \end{cases}

because we conceptually remove from \text{cnt}[K_i] first, then add it to the class of K_i'. Hence the new total is

\text{pairs}_i=\text{pairs}_0-\big(\text{cnt}[K_i]-1\big)+\big(\text{cnt}[K_i']-\mathbf{1}_{K_i'=K_i}\big).

We simply take

\max\big(\text{pairs}_0,\ \max_i \text{pairs}_i\big).

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)