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: Time Limit Exceeded

Solution code:
import itertools,sys,collections,math,random,fractions,bisect;sys.setrecursionlimit(10**7)
sr = sys.stdin.readline; P = print; P2 = lambda x: print(*x, sep="\n")
def I(i=0): t = [int(x)-i for x in sr().split()];return t
def S(): t = sr().split(); return t if len(t) > 1 else t[0]
L1,L2,L3,L4, = [],[],[],[]

N, = I()
A = I()
d = dict()
def dd(n):
    if n in d:
        return d[n]
    else:
        if n < 2:
            return 0
        else:
            d[n] = math.factorial(n) // (math.factorial(n - 2) * math.factorial(2))
            return d[n]
c = collections.Counter(A)
total = 0
for e in c.items():
    total += dd(e[1])
for e in A:
    print(total -  dd(c[e]) + dd(c[e]-1))

Submission status: Time Limit Exceeded

Solution code:
from functools import reduce
from operator import mul
import math
import copy
 
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
  
n = int(input())
l = list(map(int, input().split()))
d = {}
s_sum = {}
s_ans = {}
s = list(set(l))
m = 0
for i in range(len(s)):
    d[s[i]] = l.count(s[i])
for k, v in d.items():
    if v > 1:
        a = cmb(v, 2)
        s_ans[k] = a
        m += a
    else:
        s_ans[k] = 0
for i in range(len(l)):
    if not l[i] in d:
        print(m)
    elif l[i] in s_sum:
        print(s_sum[l[i]])
    else:
        e = copy.deepcopy(d)
        e[l[i]] -= 1
        ans = m - s_ans[l[i]]
        if e[l[i]] > 1:
            ans += cmb(e[l[i]], 2)
        s_sum[l[i]] = ans
        print(ans)

Submission status: Time Limit Exceeded

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

for i in range(n):
    a_copy = a[:]
    del a_copy[i]
    c = collections.Counter(a_copy)
    cnt = 0
    for i in c.values():
        cnt += i * (i-1) // 2

    
    print(cnt)

Submission status: Time Limit Exceeded

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


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: Time Limit Exceeded

Solution code:
import math
import copy

N = int(input())
As = input().split()
A = [0 for i in range(N)]
for i in range(N):
  A[i] = int(As[i])

# count number of each label appearing
labels = {}
for i,A_i in enumerate(A):
  if A_i in labels:
    labels[A_i] += 1
  else:
    labels[A_i] = 1

answer = [-1 for i in range(N)]
spoiler = {}
for k in range(N):
  if A[k] in spoiler:
    answer[k] = spoiler[A[k]]
  else:
    labels_now = copy.copy(labels)
    labels_now[A[k]] -= 1
    appnums = list(labels_now.values())
    answer[k] = 0
    for appnum in appnums:
      if appnum>1: answer[k] += int(appnum*(appnum-1)/2)
    spoiler[A[k]] = answer[k]

for k in range(N):
  print(answer[k])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python

n = int(input())
t = input().split()
a = []
for c in t:
    a.append(int(c))

# hash
h = {}
for v in a:
    if v in h:
        h[v] += 1
    else:
        h[v] = 1

ans = []
for c in a:
    aa = 0
    for k, v in h.items():
        vv = v
        if k == c:
            vv -= 1
        if vv > 1:
            aa += (vv*(vv-1)//2)
    print(aa)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
L = input().split()
for i in range(n):
  count = 0
  R = L[:i] + L[i+1:]
  r = len(R)
  for j in range(r-1):
    for k in range(j+1, r):
      if R[j] == R[k]:
        count += 1
  print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
an = list(map(int, input().split()))
bn = list(set(an))
allcount = 0
for i in bn:
    a = an.count(i)
    allcount += a*(a-1)//2
daburi = []
for i in an:
    daburi.append(an.count(i))
for i in daburi:
    ans = allcount - (i-1)
    print(ans)

Submission status: Time Limit Exceeded

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

for i in range(N):
  x = []
  for k in range(N):
    if i ==k :
      continue
    x.append(A[k])
    
    
    
  d = Counter(x)
  values,counts = zip(*d.most_common())
  ans = 0
  for j in range(len(counts)):
    ans += (counts[j]*(counts[j]-1))//2
    
  print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
def c2(x):
    return x * (x - 1) // 2


n = int(input())
a = list(map(lambda i: int(i) - 1, input().split()))
b = list(a.count(i) for i in range(n))
# c = list(c2(b[i]) for i in range(n))
# d = list(c2(b[i] - 1) for i in range(n))
c = []
d = []
for i in range(n):
    c.append(c2(b[i]))
    d.append(c2(b[i] - 1))
for k in range(n):
    i = a[k]
    ans = sum(c) - c[i] + d[i]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
lis = list(map(int, input().split()))
for x in range(N):
  lis_ = [lis[i] for i in range(N) if i != x]
  c = 0
  for i in range(N-2):
    for j in range(i+1, len(lis_)):
      if lis_[i] == lis_[j]:
        c+=1
  print(c)

Submission status: Time Limit Exceeded

Solution code:
import copy
n=int(input())
a=list(map(int,input().split()))
for i in range(n):
    ans = 0
    ad=copy.copy(a)
    del(ad[i])
    adset=list(set(ad))
    for j in adset:
        if(ad.count(j)>=2):
           ans += (ad.count(j)*(ad.count(j)-1)) /2
        else:
            continue
    print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

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

if len(a) == len(set(a)):
    for i in range(n):
        print(0)
else:
    kw = Counter(a)
    for i in range(n):
        ans = 0
        for k, v in kw.most_common():
            if k == a[i]:
                ans += (v - 1) * (v - 2) // 2
            else:
                ans += v * (v - 1) // 2

        print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
from operator import mul
from functools import reduce

nn = int(input())
aa = list(map(int, input().split(' ')))

counts = {}
for a in aa:
    if a not in counts:
        counts[a] = aa.count(a)


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


results = {}
for a, c in counts.items():
    if a in results:
        continue
    count = 0
    for aaa, cc in counts.items():
        if a == aaa:
            cc -= 1
        if cc <= 1:
            continue
        if cc <= 2:
            count += 1
            continue
        count += cmb(cc, 2)
    results[a] = int(count)

for k in range(nn):
    print(str(results[aa[k]]))

Submission status: Time Limit Exceeded

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


dic = {}
ans_dic = {}
for t in A:
    tmp = A.count(t)
    dic[t] = tmp
    ans_dic[t] = tmp * (tmp - 1) // 2
    
# print(dic)
# print(ans_dic)
ans = sum(ans_dic.values())
# print(ans)
for i in range(N):
    val = dic.get(A[i])
    print(ans-val+1)

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    A = list(map(int,input().split()))
    A_num = [0] * N
    for a in A:
        A_num[a-1] += 1
        
    A_product = [0] * N
    A_product_1 = [0] * N
    for i in range(N):
        a = A_num[i]
        A_product[i] = int(a * (a-1) / 2)
        if a == 0:
            A_product_1[i] = 0
        else:
            A_product_1[i] = int((a-1) * (a-2) / 2)

    for k in A:
        s = sum(A_product) - A_product[k-1] + A_product_1[k-1]
        print(s)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
N = int(input())
A = list(input().split())
for i in range(N):
  tmp = [int(x) for j,x in enumerate(A) if j != i]
  #print('tmp:',tmp)
  sumcounter = 0
  counter = Counter(tmp)
  #print('counter:',counter)
  for j in counter.keys():
    n = counter.get(j)
    #print('n:',n,'j:',j)
    sumcounter += n*(n-1)/2
  print(int(sumcounter))

Submission status: Time Limit Exceeded

Solution code:
def comb(n, k, MOD = 10 ** 9 + 7):
    if n < k:
        return 0
    if n - k < k:
        k = n - k
    comb = 1
    for x in range(n - k + 1, n + 1):
        comb = (comb * x) % MOD
    d = 1
    for x in range(1, k + 1):
        d = (d * x) % MOD
    comb *= pow(d, MOD - 2, MOD)
    return comb % MOD

def main():
    N = int(input())
    A = [int(v) for v in input().split()]
    C = [0] * (N + 1)
    M = [-1] * (N + 1)

    for i in A:
        C[i] += 1


    for i in range(N):
        C[A[i]] -= 1
        ans = 0
        for cnt in C:
            if M[cnt] == -1:
                value =  comb(cnt, 2)
                ans += value
                M[cnt] = value
            else:
                ans += M[cnt]
        C[A[i]] += 1
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import collections
import sys
import numpy as np
import copy
sys.setrecursionlimit(1000000000)
n = int(input())
a = list(map(int,input().split()))
A = collections.Counter(a)
li = []
for key,val in A.items():
    li.append([key,val])
temp = li[:]
for i in range(n):
    temp = li[:]
    ans = 0
    for j in range(len(temp)):
        if a[i] == temp[j][0]:
            temp[j][1] -= 1
            break
    for j in range(len(temp)):
        ans += ((temp[j][1])*(temp[j][1]-1))//2
    for j in range(len(temp)):
        if a[i] == temp[j][0]:
            temp[j][1] += 1
            break
    print(ans)

Submission status: Time Limit Exceeded

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

for i in range(n):
    if a[i] in d:
        d[a[i]] += 1
    else:
        d[a[i]] = 1


d_c = {}
d_2_c = {}
for i in d:
    d_c[i] = d[i] * (d[i] - 1) // 2
    d_2_c[i] = (d[i] - 1) * (d[i] - 2) // 2


for i in range(n):
    b = a[i]
    count = 0
    for j in d:
        if j != b:
            count += d_c[j]
        else:
            count += d_2_c[j]
    print(count)

Submission status: Time Limit Exceeded

Solution code:
import itertools

def main():
    n = int(input())
    As = list(map(int, input().split(" ")))
    partial = reversed(list(itertools.combinations(As, r=n-1)))
    for As_tmp in partial:
        #print(As_tmp)
        a = list(itertools.combinations(As_tmp, 2))
        b = map(lambda x: len(set(x))-2, a)
        ans = - sum(b)
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import collections
N = int(input())
A = str(input()).split(' ')
c = collections.Counter(A)

def pick(di, s):
    di[s] -= 1
    k = int(np.sum([k*(k-1)/2 for k in di.values()]))
    di[s] += 1
    return k

  
li = [pick(c, s) for s in A]
print('\n'.join(map(str, li)))

Submission status: Time Limit Exceeded

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

MOD=10**9+7
def comb(n,k):
    if n<k:
        return 0
    if n<0 or k<0:
        return 0
    k=min(n-k,k)
    ans=1
    inv=[1]*(k+1)
    if k>=1:
        ans*=(n-k+1)%MOD
    for i in range(2,k+1):
        inv[i]=MOD-inv[MOD%i]*(MOD//i)%MOD
        ans=ans*(n-k+i)*inv[i]%MOD
    return ans
cnt=[]
v=set()
yut=True
for i in range(n-1):
    if a[i]!=a[i+1]:
        yut=False
if yut:
    for i in range(n):
        print(comb(n-1,2))
    exit()
for i in range(n):
    g=a.count(a[i])
    v.add(a[i])
    cnt.append([a[i],comb(g,2)])
fg=0
cvg=[]
vsd=list(v)
for i in range(n):
    tt=vsd[fg]
    if cnt[i][0]==tt:
        cvg.append(cnt[i][1])
        if  fg<len(vsd)-1:
            fg+=1

sy=sum(cvg)-cvg[-1]
for i in range(n):
    h=a.count(a[i])
    tmp=sy-(h-1)
    ans.append(tmp)

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

Submission status: Time Limit Exceeded

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

import math
import collections

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def main():
    n = int(input())
    a_li = list(map(int, input().rstrip().split()))
    c = collections.Counter(a_li)
    total = 0
    for k, v in c.items():
        if v > 1:
            total += combinations_count(v, 2)

    for a in a_li:
        n = c[a]
        if n > 1 and n-1 > 1:
            ans = total - combinations_count(n, 2) + combinations_count(n-1, 2)
            print(ans)
        elif n > 1:
            ans = total - combinations_count(n, 2)
            print(ans)
        else:
            ans = total
            print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# from sys import stdin
import math


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


N = int(input())
A = list(map(int, input().split()))
# print(A)
d = {}
cnt = 0
for l in range(N):
    for i in range(N):
        if i != cnt:

            # else:
            d[A[i]] = d.get(A[i], 0)+1
    # print(d)
    # print(len(d))
    sum = 0
    for key,value in enumerate(d):
        # print(key,value)
        sum = sum+combinations_count(d.get(value, 0), 2)
    print(sum)
    d = {}
    cnt += 1

Submission status: Time Limit Exceeded

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)

    d = dict()
    for k in range(N):
        to_remove = a_list[k]
        retval = d.get(to_remove, 0)
        if retval != 0:
            print(retval)
            continue
        for a, c in counts.items():
            if a == to_remove:
                c -= 1

            retval += int(c * (c - 1) / 2)
        print(retval)


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)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
l = list(map(int, input().split()))
nl = {}
cl = {}
for num in l:
  if num in nl:
    nl[num] = nl[num] + 1
  else:
    nl[num] = 1
for n in nl:
  cnt = 0
  for m in nl:
    if n == m:
      if nl[m]-1 > 1:
        cnt += (nl[m]-1) * (nl[m]-2) / 2
    else:
      if nl[m] > 1:
        cnt += nl[m] * (nl[m]-1) / 2
  cl[n] = int(cnt)
for i in l:
  print(cl[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
N = int(input())
A = list(map(int,input().split()))
a = Counter(A)
b = list(a.keys())
B = [-1]*(N+1)

for i in range(N):
  count = 0
  k = A[i]
  if B[k] != -1:
    print(int(B[k]))
  else:
    for j in b:
      if j == k:
        count += (a[j]-1)*(a[j]-2)/2
      else:
        count += a[j]*(a[j]-1)/2
    B[k] = count
    print(int(count))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import math

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

c2 = math.factorial(2)

memory = {}

for k in range(1, N+1):
    a = A[:k-1] + A[k:]
    count = Counter(a)

    sum = 0
    for k, v in count.items():
        if v < 2:
            continue
        kvs = '%d,%d' % (k,v)
        if kvs in memory:
            sum += memory[kvs]
        else:
            memory[kvs] = math.factorial(v) // (math.factorial(v - 2) * c2)
            sum += memory[kvs]
    print(sum)

Submission status: Time Limit Exceeded

Solution code:
import collections

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

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

def main():
    N = int(input())
    A = list(map(int, input().split()))
    uq = list(set(A))
    ans_hash = {}
    for u in uq:
        ans = 0
        a = A[:]
        i = a.index(u)
        del a[i]
        C = Counter(a)
        val = C.values()
        for num in val:
            ans += num * (num - 1) // 2
        ans_hash[u] = ans
    for n in A:
        print(ans_hash[n])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import collections
N=int(input())
a=[]
A=list(map(int,input().split()))
a=A
c=collections.Counter(a)
d=c.most_common()
for i in range(N):
    ans=0
    for j in range(len(d)):
        if d[j][0]==A[i]:
            ans+=(d[j][1]-1)*(d[j][1]-2)//2
        else:
            ans+=d[j][1]*(d[j][1]-1)//2
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
balls = list(map(int, input().split()))
balls_count = {}
for ball_num in balls:
    if ball_num in balls_count.keys():
        balls_count[ball_num] += 1
    else:
        balls_count[ball_num] = 1

for check_ball_num in balls:
    count = 0
    for ball_num, ball_count in balls_count.items():
        if check_ball_num == ball_num:
            count += ((ball_count - 1) * (ball_count - 2) / 2)
        else:
            count += ((ball_count) * (ball_count - 1) / 2)
    print(int(count))

Submission status: Time Limit Exceeded

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

seen = [0]*n

for i in range(n):
  seen[a[i]-1] =  seen[a[i]-1] + 1
  
for i in range(n):
  count = 0
  seen[a[i]-1] = seen[a[i]-1] - 1
  for j in range(n):
    if (seen[j] == 0) or (seen[j] == 1):
      continue
    count = count + (seen[j]*(seen[j]-1))//2
    
  print(int(count))
  seen[a[i]-1] = seen[a[i]-1] + 1

Submission status: Time Limit Exceeded

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


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

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

cmemo = {}

for a in A:
    ans = 0
    for dk, dv in dmemo.items():
        if dk == a:
            dv -= 1
        
        if dv not in cmemo:
            val = ncr(dv)
            cmemo[dv] = val
        ans += cmemo[dv]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8
import itertools

def main():
    n = int(input())
    a = list(map(int, input().split()))
    a_original = a.copy()
    count = 0
    

    for i in range(n):
        a.pop(i)
        for v in itertools.permutations(a, 2):
            if v[0] == v[1]:
                count = count + 1
        print(int(count/2))
        count = 0
        a = a_original.copy()
    
    



if __name__ == '__main__' :
    main()

Submission status: Time Limit Exceeded

Solution code:
import copy, math

n = int(input())
a = input().split()

result = []

num_dict = {}

for x in set(a):
    num_dict[x] = a.count(x)

def calc(x):
    if x >= 2:
        return math.factorial(x) / (math.factorial(x - 2) * 2)
    else:
        return 0

for i in range(len(a)):
    result = 0

    temp_num_dict = copy.copy(num_dict)

    temp_num_dict[a[i]] -= 1

    for x in num_dict.keys():
        result += calc(temp_num_dict[x])

    print(int(result))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
for k in range(N):
  ans = 0
  for i in set(A):
    c = A.count(i)
    if A[k] == i:
      c -= 1
    ans += int(c*(c-1)/2)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
# from fractions import gcd
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from functools import reduce
from bisect import bisect_left, insort_left
from heapq import heapify, heappush, heappop

INPUT = lambda: sys.stdin.readline().rstrip()
INT = lambda: int(INPUT())
MAP = lambda: map(int, INPUT().split())
S_MAP = lambda: map(str, INPUT().split())
LIST = lambda: list(map(int, INPUT().split()))
S_LIST = lambda: list(map(str, INPUT().split()))
ZIP = lambda: zip(*(MAP() for _ in range(n)))

sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7


def main():
    N = INT()
    A = LIST()

    c = Counter(A)
    l = [0 for _ in range(2 * (10**5) + 7)]
    h = [0 for _ in range(2 * (10**5) + 7)]

    for k, v in c.items():
        l[k] = len(list(combinations(range(v-1), 2)))
        h[k] = len(list(combinations(range(v), 2)))

    for a in A:
        ans = sum(h) - h[a] + l[a]
        print(ans) 


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

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

setA=set(A)
NsetA=dict()
CsetA=dict()

#print(A)
#print(setA)

sum=0
for i in setA:
    NsetA[i]=A.count(i)
    if NsetA[i]>1:
        CsetA[i]=int(NsetA[i]*(NsetA[i]-1)/2)
    else:
        CsetA[i]=0
    #print(i,NsetA[i],CsetA[i])

    sum+=CsetA[i]

#print("sum=",sum)

for k in range(N):
    if NsetA[A[k]]>1:
        ans=sum-(NsetA[A[k]]-1)
    else:
        ans=sum
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
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

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

for k in range(N):
  A[k] -= (10**6)
  C = collections.Counter(A)
  A[k] += (10**6)
  values, counts = zip(*C.most_common())
  ans = 0
  for i in range(len(counts)):
    if counts[i] == 1:
      pass
    else:
      ans += cmb(counts[i],2)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import math

N = int(input())
A = list(map(int, input().split()))
d = defaultdict(lambda: 0)
for i in range(len(A)):
    d[A[i]] += 1

ans1 = 0
ans2 = 0
r = 2
calc_dict1 = {}
calc_dict2 = {}
for k, v in zip(d.keys(), d.values()):
    if v > 1:
        ans1 = math.factorial(v) // (math.factorial(v - r) * math.factorial(r))
    else:
        ans1 = 0
    if v > 2:
        ans2 = math.factorial(v - 1) // (math.factorial(v - 1 - r) * math.factorial(r))
    else:
        ans2 = 0
    calc_dict1[k] = ans1
    calc_dict2[k] = ans1 - ans2
total = sum(calc_dict1.values())
for i in range(N):
    print(total - calc_dict2[A[i]])

Submission status: Time Limit Exceeded

Solution code:
import copy
import itertools

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

for i in range(N):
    tmp = copy.copy(A)
    tmp.pop(i)

    res = 0
    for j in list(set(tmp)):
        l = tmp.count(j)
        res += len(list(itertools.combinations(list(range(l)),2)))

    print(res)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=A
for i in range(N):
  x=A[i]
  A.pop(i)
  S=list(set(A))
  sum=0
  for j in range(len(S)):
    a=A.count(S[j])
    if a!=1:
      sum+=a*(a-1)//2
  A.insert(i,x)
  print(sum)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

memo = dict()
for i in range(N):
    lst = A.copy()
    lst.pop(i)
    lst.sort()
    count=0
    if "".join(lst) not in memo:
        for i in itertools.combinations(lst, 2):
            pair = list(i)
            if pair[0] == pair[1]:
                count+=1
        memo["".join(lst)] = count
        print(count)
    else:
        print(memo["".join(lst)])
#print(memo)

Submission status: Time Limit Exceeded

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

import collections

for i in range(N):
  ans=0
  c = collections.Counter(A)
  c[A[i]]=c[A[i]]-1
  B=list(c.values())
  for k in range(len(B)):
    ans+=B[k]*(B[k]-1)/2
  print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
import math

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


def comb(n, r):
    try:
        return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
    except:
        return 0


memo = {}
for i in range(n):
    a_list = nums.copy()
    a_list.pop(i)
    cnt = 0
    for j in set(a_list):
        u_num = a_list.count(j)
        if u_num in memo:
            cnt += memo[u_num]
        else:
            calc = comb(u_num, 2)
            cnt += calc
            memo[u_num] = calc

    print(cnt)

Submission status: Time Limit Exceeded

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 calc(a):
    global C
    C[a] -= 1
    sum_ = sum([n * (n - 1) // 2 for n in C.values() if n > 1])
    C[a] += 1
    return sum_

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

for i, a in enumerate(A):
    print(calc(a))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

n = int(input())

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

ans_dict = {}
for i in range(n):
    buff = a_list[:i]
    buff.extend(a_list[i+1:])
    c = Counter(buff)

    if i in ans_dict.keys():
        print(ans_dict[i])
    else:
        tmp_ans = 0
        for key, value in c.items():
            if value == 1:
                continue
            else:
                tmp_ans += (value * (value - 1))/2
        ans_dict[i] = tmp_ans
        print(int(tmp_ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
items = list(map(int, input().split()))

number = [0] * 2000001
com = [0] * 2000001
que = deque([])
for i in range(n+1):
    nn = items.count(i)
    number[i] = nn
    com[i] = nn*(nn-1)//2
sumc = sum(com)
que.extend(items)

while que:
    q = que.popleft()
    if number[q] <2:
        print(sumc-com[q])
    else:
        print(sumc-number[q]+1)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

total = 0
for i, j in itertools.combinations(A, 2):
    if i == j:
        total += 1

for k, val in enumerate(A):
    count = 0
    for i, v in enumerate(A):
        if k == i:
            continue
        if val == v:
            count += 1
    print(total - count)

Submission status: Time Limit Exceeded

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

c = dict(collections.Counter(a))

for i in a:
    temp = c[i] - 1
    ans = (temp * (temp - 1)) // 2
    for v in c.values():
        ans += (v * (v - 1)) // 2
    ans -= (c[i] * (c[i] - 1)) // 2
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
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

##################################################

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

ans = 0

for i in range(n):
    a1 = a[:int(i)] + a[int(i + 1):]
    #print(a1) #a1 check
    for j in range(n):
        b = a1.count(j + 1)
        if b <= 1:
            pass
        else:
            ans += cmb(b, 2)
        #print(ans)
    print(ans)

    ans = 0 # initiation of the variant 'ans'

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().split()))
k=0
b=sorted(a)
for i in range(b[-1]):
  v=b.count(i+1)
  k+=v*(v-1)//2
for i in a:
  ans=k-a.count(i)+1
  print(ans)