Problem:


Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.  

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

3 \leq N \leq 2 \times 10^5

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5



Sample input:
5
1 1 2 1 2


Sample output:
2
2
3
2
3

Submission status: Accepted

Solution code:
import collections
import math

def comb(n, r):
    if n < 2:
        return 0
    else:
        return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))


N = int(input())
L = input().split(" ")

c = collections.Counter(L)

d = {}
tmp_total = 0 

memo1 = {}
L2 = {}

for i in c:
    if c[i] not in memo1.keys():
        tmp = comb(c[i], 2)
        memo1[c[i]] = tmp
        tmp_total += tmp
    else:
        tmp_total += memo1[c[i]]
        
total = tmp_total

for i in L:
    ans = total - memo1[c[i]] + memo1[c[i]]*(c[i]-2)//c[i]
    print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = [i for i in map(int, input().split())]

#print(n)
#print(a)

# ボールに書かれた数の出現数
syutsugen_counts = [0] * n
# 同じボールを選ぶ方法
choice_counts = [0] * n
# ボールが1つ減った時に同じボールを選ぶ方法
decrease_one_choice_counts = [0] * n

total_choice_count = 0

for i in range(n):
  ball_num = a[i] - 1
  syutsugen_counts[ball_num] += 1

for i in range(n):
  syutsugen_count = syutsugen_counts[i]
  if syutsugen_count < 2:
    continue
  # 出現数が2以上から同じボールを選べる
  choice_count = int((syutsugen_count * (syutsugen_count-1) / 2))
  choice_counts[i] = choice_count
  total_choice_count += choice_count
  
  # 出現数が2の場合はここまで
  if syutsugen_count < 3:
    continue
  
  # 出現数が3以上なら一つ減った場合でも同じボールが選べる
  decrease_one = syutsugen_count - 1
  decrease_one_choice_count = int((decrease_one * (decrease_one-1) / 2))
  decrease_one_choice_counts[i] = decrease_one_choice_count

for i in range(n):
  ball_num = a[i] - 1
  choice_count = choice_counts[ball_num]
  decrease_one_choice_count = decrease_one_choice_counts[ball_num]
  print(total_choice_count - choice_count + decrease_one_choice_count)

Submission status: Accepted

Solution code:
# coding: utf-8
from collections import Counter as co
n=int(input())
a=[int(x) for x in input().split()]
d=dict(co(a))
#print(d)
p={}
for x in d:
    y=d[x]
    p[x]=max((y*(y-1))//2,0)
#print(p)
ss=0
for x in p:
    ss+=(p[x])
#print(ss)
for i in a:
    x=d[i]-1
    #print(x,end=' ')
    y=max(x*(x-1)//2,0)
    print(ss-p[i]+y)
    #dd[i]=max(dd[i]-1,)
    #print(ss-(p[i]-1)

Submission status: Accepted

Solution code:
n = int(input(''))
stra = input('')

alist = stra.split(' ')
dic = {}
for i in range(0,len(alist)):
  if alist[i] in dic.keys():
    dic[alist[i]]+=1
  else:
    dic[alist[i]] = 1

all_cnt = 0    
for k,v in dic.items():
  all_cnt += (v*(v-1))/2

    
for k in range(0,n):
  cnt = 0
  key = alist[k]
  minus_cnt1 = (dic[key] * (dic[key]-1))/2
  minus_cnt2 = ((dic[key]-1) * (dic[key]-2))/2
  print(int(all_cnt -  minus_cnt1 + minus_cnt2))

Submission status: Accepted

Solution code:
from sys import stdin
from collections import Counter

def main():

    input = stdin.readline

    N = int(input())

    A = [0] * N

    A = list(map(int,input().split()))

    all_case = 0

    num_all = Counter(A) 

    for k in num_all.values():
        all_case += (k * (k-1)) // 2

    for i in A:
        ans = all_case - (num_all[i] - 1)
        print(ans)
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())

count = [0 for _ in range(200000)]
line = [int(i) for i in input().split()]
pattern = [0 for _ in range(200000)]
sum = 0
# index = []

for i in line:
	# if count[i] == 0:
		# index.append(i)
	count[i] += 1

for num in count:
	sum += (num*(num-1))//2



for i in line:
	if count[i] > 2:
		result = sum - (count[i]-1) 
	elif count[i] == 2:
		result = sum - 1
	elif count[i] == 1:
		result = sum
	print(result)

Submission status: Accepted

Solution code:
import sys
import collections
input = sys.stdin.readline

def main():
    N = int(input())
    A = list(map(int, input().split()))

    c = collections.Counter(A)

    s = 0
    for (k, v) in c.items():
        s += (v * (v -1) //2)

    for x in A:
        print(s - (c[x] - 1))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import Counter

def cmb(n, r, mod=10**9+7):
    return n * (n - 1) // 2



N = int(input())
ball_com = [0] * (N + 1)
balls = list(map(int, input().split()))
balls_counter = Counter(balls)
for key , val in balls_counter.items():
    ball_com[key - 1] = cmb(val, 2)

cmb_sum = sum(ball_com)
for ball in balls:
    print(cmb_sum - ball_com[ball - 1] + cmb(balls_counter[ball] - 1, 2))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
lis = [0] * (n *3)
for i in range(n):
    lis[a[i]] += 1
#print(lis)
cum = [0] * len(lis)
for i in range(n*3):
    cnt = (lis[i] * (lis[i]-1)) // 2
    cum[i] = cnt
ans = sum(cum)
cum2 = [0] * len(lis)
for i in range(2,(n*3)):
    cum2[i] = (i * (i-1)) // 2
#print(cum)
#print(cum2)
#cum2がiに対しての組み合わせ
#cumが要素数に対しての組み合わせ
#lisがiの数
#print(ans)
for i in range(n):
    print(ans - (cum2[lis[a[i]]]-cum2[lis[a[i]]-1]))

Submission status: Accepted

Solution code:

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

def sum(num):
    if num < 2:
        return 0
    s = 0
    for i in range(num):
        s += i
    return s

x = [0] * (n+1)

for i in range(n):
    x[a[i]] += 1

ans = 0

for i in range(n+1):
    ans += sum(x[i])

for i in range(n):
    ans2 = ans - (x[a[i]]-1)
    print(ans2)

Submission status: Accepted

Solution code:
import bisect

N = int(input())
A = [int(x) for x in input().split()]

B = sorted(A)
cnt = [0] * (N+1)
for k in range(1, N+1):
    cnt[k] = bisect.bisect_left(B, k+1)
for k in range(N):
    cnt[-1-k] -= cnt[-2-k]

ALL = 0
for i in range(1, N+1):
    ALL += cnt[i]*(cnt[i]-1)//2

for k in range(N):
    ans = ALL - cnt[A[k]]*(cnt[A[k]]-1)//2 + (cnt[A[k]]-1)*((cnt[A[k]]-1)-1)//2
    print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))

B={}
for i in range(N):
    if A[i] not in B:
        B[A[i]]=1
    else:
        B[A[i]]+=1

total=0

for k,v in B.items():
    total+=v*(v-1)//2

for i in range(N):
    ans=total
    ans-=B[A[i]]-1
    print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

def main():
    n = int(input())
    A = [int(e) for e in input().split()]

    Da = Counter(A)
    cnt = 0
    for v in Da.values():
        cnt += v*(v - 1)//2

    for i in range(n):
        print(cnt - (Da[A[i]] - 1))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import collections
N = int(input())
A = list(map(int,input().split()))
ikutu = collections.Counter(A)

#要素数リスト
Ac = [ikutu[x] for x in ikutu]

#抜かない時の組み合わせ数
kumi = 0
for i in range(len(Ac)):
    if Ac[i] != 1:
        kumi += (Ac[i]*(Ac[i]-1))//2

for j in range(N):
    if ikutu[A[j]] != 1:
        Ans = kumi - ((ikutu[A[j]])*(ikutu[A[j]]-1))//2 + ((ikutu[A[j]]-1)* (ikutu[A[j]]-2))//2
    else:
        Ans = kumi
    print(Ans)

Submission status: Accepted

Solution code:
import collections

N = int(input())
A = list(map(int, input().split()))

ctr_A = collections.Counter(A).most_common()
less_A = collections.Counter(A)

total = 0

for i in range(len(ctr_A)):
    n = ctr_A[i][1]
    total += n * (n - 1) // 2

for i in range(N):
    summ = total
    num = A[i]
    n = less_A[num]

    if (n == 2):
        summ -= 1
    else:
        new = (n - 1) * (n - 2) // 2
        old = n * (n - 1) // 2
        summ += new - old
    
    ans = max(0, summ)

    print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

N = int(input())

A = list(map(int, input().split()))

set_A = set(A)

ans = 0
sens = {}
for value in Counter(A).items():
    key = value[0]
    v = value[1]
    ans += v * (v - 1) /2
    sens[key] = v * (v - 1) /2 - (v - 1) * (v - 2)/2

for a in A:
    print(int(ans - sens[a]))

Submission status: Accepted

Solution code:
n = int(input())
k = [int(i) for i in input().split()]
pair = {}

for i in range(n):
    pair.setdefault(k[i], []).append(i)

sum = 0
for value in pair.values():
    l = len(value)
    sum += l*(l-1)//2

for i in range(n):
    len_pair = len(pair[k[i]])
    if len_pair != 1:
        ans = sum - ((len_pair*(len_pair-1)//2)-((len_pair-1)*(len_pair-2)//2))
        print(ans)
    else:
        print(sum)

Submission status: Accepted

Solution code:
from scipy.misc import comb
N,*A = map(int,open(0).read().split())
d = {}
for i in A:
    d[i]= d[i]+1 if i in d else 1
count_d = {}
sum = 0
for k,v in d.items():
    count_d[k] = comb(v,2,exact=True)
    sum += count_d[k] 
 
for i in A:
    if count_d[i]>=1:
        print(sum - (d[i]-1))
    else:
        print(sum)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))

listlist = []
result = {}#辞書型配列の作成
for i in range(0,n):
  num = a[i]
  if num in result:
    result[num] = result[num] + 1
  else:
    result[num] = 1
    
vals = list(result.values())
l = len(vals)

count = 0
for j in range(0,l):
  attack = vals[j]
  count = count + attack*(attack-1)//2#組み合わせ総数

for k in range(0, n):
  block = a[k]
  if block in result:
    fighter = result[block]
    listlist.append(count - fighter +1)
  else:
    listlist.append(count)
     
for si in listlist:
  print(si)

Submission status: Accepted

Solution code:
from functools import lru_cache

N = int(input().strip())
A = [int(v) for v in input().strip().split()]
C = {}


@lru_cache(maxsize=None)
def pair(k):
    return k * (k - 1) // 2

@lru_cache(maxsize=None)
def calc(s, a):
    return s - pair(C[a]) + pair(C[a] - 1)

for a in A:
    C.setdefault(a, 0)
    C[a] += 1

S = sum([pair(v) for v in C.values()])

for a in A:
    print(calc(S, a))

Submission status: Accepted

Solution code:
#


def main():
    n = int(input())
    a = [int(s) for s in input().split(" ")]
    counts = {}
    for i in a:
        if i in counts:
            counts[i] += 1
        else:
            counts[i] = 1
    # これだとTLE
    # results = {}
    # for i in a:
    #     if i in results:
    #         print(results[i])
    #         continue
    #     count = 0
    #     for k, v in counts.items():
    #         if k == i:
    #             v -= 1
    #         if v > 1:
    #             count += (v * (v - 1) // 2)
    #     print(count)
    #     results[i] = count
    total = 0
    comb = {}
    for k in counts:
        if counts[k] > 1:
            y = counts[k]
            x = (y * (y - 1)) // 2
            total += x
            comb[k] = x
        else:
            comb[k] = 0
    for i in a:
        print(total - (counts[i] - 1))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def comb(a):
    if a < 2:
        return 0
    else:
        return a * (a-1) // 2


N = int(input())
A = list(map(int, input().split()))
ans = []
total = 0
dct = {}
for a in A:
    if (dct.get(a) != None):
        total -= comb(dct[a])
        dct[a] += 1
        total += comb(dct[a])
    else:
        dct[a] = 1
for a in A:
    print(total - comb(dct[a])+comb(dct[a]-1))

Submission status: Accepted

Solution code:
from collections import *
n=int(input())
numbers=input().rstrip().split(" ")
S=Counter(numbers)
#print(S)
sigma=0
#print(S["1"])
for i in S.values():
    sigma+=i*(i-1)/2
alls=int(sigma)
answers=[]
for number in numbers:
    minus=S[number]-1
    answers.append(alls-minus)
for answer in answers:
    print(answer)

Submission status: Accepted

Solution code:
N = int(input())
P = list(map(int,input().split()))
import collections
c = collections.Counter(P)
t = 0
for j in c.values():
    t = t+j*(j-1)/2
for i in range(N):
    t1 = t -(c[P[i]]-1)
    print(int(t1))

Submission status: Accepted

Solution code:
import collections

def c2c(n):
    return n*(n-1)//2

N = int(input())
A = list(map(int,input().split()))
c = collections.Counter(A)
c_l = list(c.values())
d2 = sum([c2c(i) for i in c_l])
#print(d2)

for i in range(len(A)):
    print(d2-(c[A[i]]-1))

Submission status: Accepted

Solution code:
def conbination_2(n):
  if n <= 1:
    return 0
  else:
    return int(n * (n - 1) / 2)


N = int(input())
A = list(map(int,input().split()))
S = 0
Count = [0] * N

for i in range(N):
  Count[A[i] - 1] += 1
  
for i in range(N):
  S += conbination_2(Count[i])
  
for i in range(N):
  Ans = S - (Count[A[i] - 1] - 1)
  print(Ans)

Submission status: Accepted

Solution code:
'''
.append(要素) リストに要素を追加
.extend(リスト) リストを連結する
.insert(場所,要素) 指定した場所に要素追加
del 配列名[場所]
-1で末尾で末尾から一つ前

sort()
sorted(reverse=true)

配列の初期化
配列名=[a]*n+[b]*m

Decimal()
'''

from sys import stdin
from itertools import accumulate, dropwhile, takewhile, groupby
import bisect
import copy
import math
from functools import reduce
from operator import mul
from collections import Counter

N = int(stdin.readline().rstrip())
A = [int(s) for s in stdin.readline().rstrip().split()]

B = copy.copy(A)
B.sort()

d = {}
e = {}
count = 0
pos = 0
for el in B:
    if pos == 0:
        count += 1
    elif B[pos] == B[pos - 1]:
        count += 1
    elif B[pos] != B[pos - 1]:
        e[str(el-1)] = int(count*(count-1)/2)
        count = 1
    d[str(el)] = count
    pos += 1
    if len(B) == pos:
        e[str(el)] = int(count*(count-1)/2)
res = 0
for el in e.values():
    res += el
for el in A:
    print(res-int((d[str(el)]*(d[str(el)]-1)/2)) +
          int(((d[str(el)]-2)*(d[str(el)]-1)/2)))

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
cnt = [0 for _ in range(n+1)]


def num_comb(a):
    return a * (a - 1) // 2


for i in range(n):
    cnt[a[i]] += 1

num_combs = [num_comb(cnt[i]) for i in range(n+1)]
total = sum(num_combs)

for i in range(n):
    res = total - num_combs[a[i]] * 2 // cnt[a[i]]
    print(res)

Submission status: Accepted

Solution code:
N = int(input())
A_list = list(map(int, input().split()))
from collections import Counter

counter = Counter(A_list)
result = 0
for (key, value) in counter.items():
    #print(key,value)
    result += int(value * (value - 1) / 2)

#print(result)
for a in A_list:
    value = counter.get(a)
    #print(value)
    answer = result - (int(value * (value - 1) / 2)) + int((value - 1) * (value - 2) / 2)
    print(answer)

Submission status: Accepted

Solution code:
import collections

N = int(input())
A = list(map(int, input().split()))

c = collections.Counter(A)
cv = c.values()
ck = c.keys()

ori=0
for x in cv:
    ori += (x-1) * ((x-1)+1) // 2


for i in range(N):
    tmp = A[i]
    print(ori - (c[tmp]-1))

Submission status: Accepted

Solution code:
import collections
n = int(input())
a = list(map(int,input().split()))
c = collections.Counter(a)
s = 0
for v in c.values():
    if v >= 2:
        s += v*(v-1)//2

for i in range(n):
    k = a[i]
    ans = s
    v = c[k]
    if v >= 3:
        ans -= v-1
    if v <= 2:
        ans -= v*(v-1)//2
    print(ans)

Submission status: Accepted

Solution code:
import math

def permutations_count(n, r):
    if (n < 2):
        return 0
    else:
        return math.factorial(n) // math.factorial(n - r)

N = int(input())
A = list(map(int, input().split()))

bar = {}

for i in range(N):
    if (A[i] in bar):
        bar[A[i]] = bar[A[i]] + 1
    else:
        bar[A[i]] = 1

partOfNum = {}
lackPartOfNum = {}

for j in bar.keys():
    tmp = permutations_count(bar[j], 2)
    partOfNum[j] = int(tmp / 2)
#   tmp = permutations_count(bar[j] - 1, 2)
    lackPartOfNum[j] = partOfNum[j] - (bar[j] - 1)

allSum = 0
for l in partOfNum.keys():
    allSum += partOfNum[l]

for i in range(N):
    print(allSum - partOfNum[A[i]] + lackPartOfNum[A[i]])

Submission status: Accepted

Solution code:
# coding: utf-8

n = input()
an = map(int, raw_input().split())

d = {}
for a in an:
    if not a in d:
        d[a] = 1
    else:
        d[a] += 1
#print d

sa = 0
for ai in d:
    si = d[ai] * (d[ai] - 1) // 2
    sa += si

for a in an:
    a1 = d[a] * (d[a] - 1) // 2
    a2 = (d[a] - 1) * (d[a] - 2) // 2

    print sa - a1 + a2

Submission status: Accepted

Solution code:
from collections import Counter


def choose(n: int) -> int:
    if n < 2:
        return 0
    else:
        return (n * (n - 1)) // 2


N = int(input())
A = list(map(int, input().split()))
c = Counter(A)
d = {key: choose(value) for key, value in c.items()}
if len(d) > 1:
    sum_d = sum(d.values())
    for a in A:
        print(sum_d - d[a] + choose(c[a] - 1))
else:
    ans = choose(N - 1)
    for _ in range(N):
        print(ans)

Submission status: Accepted

Solution code:
N = int(input())
list = list(map(int,input().split()))
kosuu = [0] * N
kosuuu = [0] * N
total = 0
listed = sorted(list)
listed.append(-1)
i = 0
count = 1
while i < N:
    a = listed[i]
    if a == listed[i+1]:
        count += 1
    else:
        kosuu[a-1] = count
        total += ( count * (count-1) ) //2
        count = 1
    i += 1
for i in range(N):
    a = kosuu[list[i]-1]
    print(total-a*(a-1)//2 + (a-1)*(a-2)//2)

Submission status: Accepted

Solution code:
from collections import Counter

def nCk(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

n = int(input())
a = list(map(int, input().split()))
b = Counter(a)
c = {}
d = {}
for k, v in b.items():
    c[k] = nCk(v, 2) if v > 1 else 0
    d[k] = nCk(v-1, 2) if v > 2 else 0
total = sum(c.values())
for i in range(n):
    ans = total - c[a[i]] + d[a[i]]
    print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict
def main():
    n=int(input())
    A=list(map(int,input().split()))
    d=defaultdict(int)
    m=max(A)
    for a in A:
        d[a]+=1
    c=0
    for i in range(1,m+1):
        if d[i]>=2:
            c+=(d[i]*(d[i]-1))//2
    for a in A:
        if d[a]<2:
            print(c)
        else:
            print(c-(d[a]-1))
    
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import collections
N = int(input())
A = list(map(int, input().split()))
wlists = collections.Counter(A)
sum_num = 0
for i in wlists:
  sum_num += wlists[i] * (wlists[i] - 1) // 2
for i in range(N):
  num = sum_num - wlists[A[i]] * (wlists[A[i]] - 1) // 2
  if wlists[A[i]] > 1:
    num += (wlists[A[i]] - 1) * (wlists[A[i]] - 2) // 2
  print(num)

Submission status: Accepted

Solution code:
from collections import defaultdict
from sys import stdin


def main():
    input = lambda: stdin.readline()[:-1]
    N = int(input())
    A = tuple(map(int, input().split()))

    ball = defaultdict(int)
    for i in A:
        ball[i] += 1
    total = 0
    sel = defaultdict(int)
    for k, v in ball.items():
        n = v * (v - 1) // 2
        sel[k] = n
        total += n
    for a in A:
        n = ball[a] - 1
        x = (n * (n - 1)) // 2
        print(total - (sel[a] - x))


main()

Submission status: Accepted

Solution code:
from copy import deepcopy
dp = {0: 0}

N = int(input())
A = list(map(int, input().split()))

balls = {}
fact = 1
for (i, a) in enumerate(A):
  count = i+1
  dp[count] = count * (count-1) // 2
  if a in balls:
    balls[a] += 1
  else:
    balls[a] = 1

res = 0
for count in balls.values():
  res += dp[count]

for a in A:
  print(res - dp[balls[a]] + dp[balls[a]-1])

Submission status: Accepted

Solution code:
from collections import Counter
'''
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result
'''

def cmb(n,r):
    return n*(n-1)//2

N=int(input())
A=list(input().split())
c=Counter(A)
itms=list(c.items())#
lenC=len(c)
num=0

for i in range(lenC):
    itmsi=itms[i][1]
    if itmsi>=2:
        num+=cmb(itmsi,2)


for i in range(N):
    num2=c[A[i]]
    if num2>=3:
        print(num-cmb(num2,2)+cmb(num2-1,2))

    elif num2==2:
        print(num-1)
    else:
        print(num)

Submission status: Accepted

Solution code:
from collections import deque
from collections import Counter
from itertools import product, permutations,combinations
from operator import itemgetter
from heapq import heappop, heappush
from bisect import bisect_left, bisect_right, bisect
#pypyではscipy, numpyは使えない
#from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, minimum_spanning_tree
#from scipy.sparse import csr_matrix, coo_matrix, lil_matrix
#import numpy as np
from fractions import gcd
from math import ceil,floor, sqrt, cos, sin, pi, factorial
import sys
input = sys.stdin.readline
#文字列のときはうまく行かないのでコメントアウトすること
sys.setrecursionlimit(2147483647)

def main():
  n = int(input())
  a = list(map(int, input().split()))
  s = Counter(a)
  subete = 0
  herasu = [0]*(n+1)
  for key, value in s.items():
    if value>=2:
      subete += factorial(value)/(2*factorial(value-2))
      herasu[key] = value-1
  for i in a:
    print(int(subete-herasu[i]))
  

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import collections

n = int(input())
a = list(map(int, input().split()))
c = collections.Counter(a)

ans = {}
comb = 0
# 全てのキーに対して処理を実施
for k in c.keys():
  comb += int(c[k]*(c[k]-1)/2)
for k in c.keys():
  ans[k] = comb-(c[k]-1)

for i in range(n):
  print(ans[a[i]])

Submission status: Accepted

Solution code:
import collections

n = int(input())

a = list(map(int, input().split()))

c = collections.Counter(a)
total = 0
for i in c:
    total += c[i]*(c[i]-1)//2


for i in range(n):
    target = c[a[i]]
    print(total - target*(target-1)//2 + (target-1)*(target-2)//2)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[int]"):
    nums = [0] * N
    for i in A:
        nums[int(i) - 1] += 1
    
    sum = 0
    for num in nums:
        sum += num * ( num - 1 ) // 2

    for k in range(0, N):
        old = nums[int(A[k]) - 1]
        new = old - 1
        ans = sum - (old * (old - 1) // 2 - new * (new - 1) // 2)
        print(ans)
    

    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))

cnt = 0
L = [0] * (N + 1)
for a in A:
    L[a] += 1

for l in L:
    cnt += l * (l - 1) // 2

for a in A:
    ans = cnt - (L[a] * (L[a] - 1) // 2) + ((L[a] - 1) * (L[a] - 2) // 2)
    print(ans)

Submission status: Accepted

Solution code:
N = int(input())

A0 = list(map(int,input().split()))

A=sorted(A0)
A.append(0)

N1={}

c = 1
for i in range(N):
#    print(A[i],A[i+1])
    if A[i] == A[i+1]:
        c += 1
    else:
        N1[A[i]] = c
        c = 1
#mydict["peach"] = 4
#print(A)
#print(N1)

N2={}
for i in N1.keys():
#    print(i,N1[i])
    if N1[i] ==1:
        N2[i] = (0,0)
    else:
        N2[i] = (N1[i]*(N1[i]-1)/2,(N1[i]-1)*(N1[i]-2)/2)

T1 = 0
for i in N2.keys():
    T1 += N2[i][0]

for i in range(N):
    T2 = int(T1 - N2[A0[i]][0]+N2[A0[i]][1])
    print(T2)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))
import collections
from operator import mul
from functools import reduce

def cmb(n,r):
    r = min(n-r,r)
    if r == 0: return 1
    over = reduce(mul, range(n, n - r, -1))
    under = reduce(mul, range(1,r + 1))
    return over // under

def main():
    N = int(input())
    A = input_nums()
    C = collections.Counter(A)

    X = {}
    Y = {}
    maxv = 0
    for k, v in C.items():
        if v >= 2:
            X[k] = cmb(v, 2)
            maxv += X[k]
        else:
            X[k] = 0
        if v >= 3:
            Y[k] = cmb(v-1, 2)
        else:
            Y[k] = 0

    ANS = {}
    for k in Y.keys():
        ANS[k] = maxv - (X[k] - Y[k])

    for a in A:
        print(ANS[a])

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int , input().split()))

from collections import defaultdict
c = defaultdict(int)
for ai in a:
    c[ai] += 1

class Combination:
    def __init__(self, N=2*10**5, mod=67280421310721):
        self.mod = mod
        self.N = N
        self.fact = [1, 1]  # fact[n] = (n! mod p)
        self.factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
        self.inv = [0, 1]  # factinv 計算用
        for i in range(2, N + 1):
            self.fact.append((self.fact[-1] * i) % mod)
            self.inv.append((-self.inv[mod % i] * (mod // i)) % mod)
            self.factinv.append((self.factinv[-1] * self.inv[-1]) % mod)

    def nCr(self, n, r):
        if (r < 0) or (n < r):
            return 0
        r = min(r, n - r)
        return self.fact[n] * self.factinv[r] * self.factinv[n-r] % self.mod

comb = Combination()

t = 0
for ci in c:
    t += comb.nCr(c[ci],2)

for ai in a:
    print(t - comb.nCr(c[ai],2) + comb.nCr(c[ai]-1,2))

Submission status: Accepted

Solution code:
from collections import Counter
import sys
n=int(input())
s=sys.stdin.readlines()
A=list(map(int,s[0].split()))
C=Counter(A)
R=0
for v in C.values():
    R+=v*(v-1)//2
for i in range(n):
    r=C[A[i]]
    X=R
    if r>=2:
        x=((r-1)*(r-2)//2-(r)*(r-1)//2)
        X+=x
    print(X)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
d = {}
d_sum = {}
for i in range(N):
  if A[i] in d:
    d[A[i]] += 1
    d_sum[A[i]] += d[A[i]] - 1
  else:
    d[A[i]] = 1
    d_sum[A[i]] = 0
#print(A, d,d_sum)
#print(sum(A), sum(d.values()))
ans = sum(d_sum.values())
for i in range(N):
  print(ans - (d[A[i]] - 1))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import collections
import itertools


def main():
    n = int(input())
    a_i = tuple(map(int, input().split()))

    count_item = {}
    all_cnt = 0
    for items in collections.Counter(a_i).items():
        if items[1] >= 2:
            now_cnt = int(items[1] * (items[1] - 1) / 2)
            pre_cnt = now_cnt - items[1] + 1
            count_item[items[0]] = (now_cnt, pre_cnt)
            all_cnt += now_cnt
        else:
            count_item[items[0]] = (0, 0)

    for k in a_i:
        items = count_item[k]
        print(all_cnt - (items[0] - items[1]))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(4100000)

import math

import logging

logging.basicConfig(level=logging.DEBUG)

logger = logging.getLogger(__name__)

from collections import Counter


def resolve():
    # S = [x for x in sys.stdin.readline().split()][0]  # 文字列 一つ
    N = [int(x) for x in sys.stdin.readline().split()][0]  # int 一つ
    # N, D = [int(x) for x in sys.stdin.readline().split()]  # 複数int
    a_list = [int(x) for x in sys.stdin.readline().split()]  # 複数int

    # grid = [list(sys.stdin.readline().split()[0]) for _ in range(N)]  # 文字列grid
    # v_list = [int(sys.stdin.readline().split()[0]) for _ in range(N)]
    # grid = [[int(x) for x in sys.stdin.readline().split()]
    #         for _ in range(N)]  # int grid

    logger.debug('{}'.format([]))

    counts = Counter(a_list)

    retval = 0
    for a, c in counts.items():
        retval += int(c * (c - 1) / 2)

    for k in range(N):
        to_remove = a_list[k]
        c = counts[to_remove]
        print(retval - c * (c - 1) // 2 + (c - 1) * (c - 2) // 2)


if __name__ == "__main__":
    resolve()

# AtCoder Unit Test で自動生成できる, 最後のunittest.main は消す
# python -m unittest template/template.py で実行できる
# pypy3 -m unittest template/template.py で実行できる

import sys
from io import StringIO
import unittest


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """5
1 1 2 1 2"""
        output = """2
2
3
2
3"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """4
1 2 3 4"""
        output = """0
0
0
0"""
        self.assertIO(input, output)

    def test_入力例_3(self):
        input = """5
3 3 3 3 3"""
        output = """6
6
6
6
6"""
        self.assertIO(input, output)

    def test_入力例_4(self):
        input = """8
1 2 1 4 2 1 4 1"""
        output = """5
7
5
7
7
5
7
5"""
        self.assertIO(input, output)