Problem:


Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.



Sample input:
3
acornistnt
peanutbomb
constraint


Sample output:
1

Submission status: Accepted

Solution code:
def main(sample_file = ''):

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """
    
    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        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 combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter #sort 
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors
        
        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.
        
        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)
    
    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # put inputs between specific values (almost as quickly)
        # ex) S = [-INF] + [int(r()) for _ in range(A)] + [INF]
        # open(0).read() is sometimes useful:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    # for test
    if sample_file:
        sys.stdin = open(sample_file)
        
    # ----------------------------------
    # main

    N = int(r())
    S = [0] * N
    for i in range(N):
        s = r()
        s = sorted(s)
        S[i] = s
    S.sort()
    cnt = 0
    tmp = ''
    ans = 0
    for i in S:
        if i == tmp:
            cnt += 1
        else:
            if cnt >= 2:
                ans += combinations_count(cnt, 2)
            cnt = 1
        tmp = i
    else:
        if cnt >= 2:
            ans += combinations_count(cnt, 2)
    print(ans)
    
    # to finish code, use return instead of exit()
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # three methods for loop: keys(), values(), items()
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
my_dict = {}
for i in range(n):
    sorted_str = ''.join(sorted(list(input())))
    if not sorted_str in my_dict:
        my_dict[sorted_str] = 1
    else:
        my_dict[sorted_str] += 1
        
        
        
ret = 0
my_list = [i for i in my_dict.values() if i>1]
for j in my_list:
    ret +=  (j * (j-1) // 2)
    
    
print(ret)

Submission status: Accepted

Solution code:
import collections

N = int(input())
s_list = ["".join(sorted(input())) for i in range(N)]
s_list = sorted(s_list)

count = 0

c = collections.Counter(s_list)

for item in c:
  for pair in range(c[item]):
    count += pair
        
print(count)

Submission status: Accepted

Solution code:
def main():
    n=int(input())
    res = {}
    ans = 0
    for i in range(n):
        c = str(sorted(input()))
        if c not in res.keys():
            res[c] = 1
        else:
            res[c] += 1
    for i in res.values():
        ans += int(i*(i-1)/2)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter
n = int(input())
ct_ls = []
for i in range(n):
    ct_ls.append("".join(sorted(input())))
ct = Counter(ct_ls)
_ct = 0
for n in ct.values():
    if n >= 2:
        _ct += n * (n - 1) / 2
print(int(_ct))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# 
import math
import sys
import itertools
import numpy as np

# いっこ入力
n =int(input())

# n行の複数列ある数値を二次元配列へ。x[n][?]
s = [list(input()) for i in range(n)] 
t = [0]*n
#print(s)
for i in range(n):
    a = sorted([s[i][ii] for ii in range(10)])
    for j in range(10):
        t[i] = t[i] * 26 + ord(a[j]) - ord('a')
t = sorted(t)
same = 1
mae = -1
answer = 0
#print(t)
for i in range(n):
    if t[i]==mae:
        same += 1
    else:
        answer += same * (same-1) // 2
        same = 1
        mae = t[i]
answer += same * (same-1) // 2
print(answer)

Submission status: Accepted

Solution code:
def c_green_bin(N, S):
    s = sorted([''.join(sorted(word)) for word in S])
    right = 1
    ans = 0
    for left in range(N):
        while right < N and s[left] == s[right]:
            right += 1
        ans += right - 1 - left
        if left + 1 == right:
            right += 1
    return ans

N = int(input())
S = [input() for _ in range(N)]
print(c_green_bin(N, S))

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]

def main():
    n = II()
    c = defaultdict(int)
    for i in range(n):
        c["".join(sorted(S()))] += 1
    ans = 0
    for k, v in c.items():
        ans += int(v * (v - 1) /2)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

debug = True
debug = False

def dprint(*objects):
    if debug == True:
        print(*objects)

def solve():
    N = II()
    s_list = []
    for i in range(N):
        s = SI()
        s = sorted(s)
        s_list.append(''.join(s))

    s_list = sorted(s_list)
    dprint(s_list)

    cnt_list = []
    cnt = 0
    current = ''
    for s in s_list:
        if current != s:
            cnt_list.append(cnt+1)
            current = s
            cnt = 0
        else:
            cnt += 1
    cnt_list.append(cnt+1)
    dprint(cnt_list)


    ans = 0
    for cnt in cnt_list:
        ans += cnt*(cnt-1)//2

    print(ans)

solve()

Submission status: Accepted

Solution code:
from collections import defaultdict
        

obj = defaultdict(lambda: 1)

N=int(input())
ANA=[]
L=set([])
for i in range(N):
    k="".join(sorted([x for x in input()]))
    if k in L:
        obj[k]+=1
    else:
        L.add(k)

result=0
for i in obj.values():
    if i and i-1:
        result+=i*(i-1)/2
    
print(int(result))

Submission status: Accepted

Solution code:
N = int(input())

S = {}
for i in range(N):
  s = [0 for _ in range(26)]
  tmp = input()
  for j in range(10):
    s[ord(tmp[j]) - ord("a")] += 1
  
  s = ",".join(map(str, s))
  if s in S:
    S[s] += 1
  else:
    S[s] = 1

ans = 0
for v in S.values():
  if v > 1:
    for i in range(1, v):
      ans += i

print(ans)

Submission status: Accepted

Solution code:
import collections

n = int(input())

s_sorted = []
for i in range(n):
    s_sorted.append(''.join(sorted(list(input()))))
    # s.append(input())

# print(s)

c = collections.Counter(s_sorted)
# print(c.values())

ans = 0
for i in c.values():
    ans += i * (i - 1) / 2
    # print(i)

print(int(ans))

Submission status: Accepted

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

n = int(input())

d = {}
for _ in range(n):
    si = input()
    l = [0 for i in range(26)]
    for c in si:
        l[ord(c) - ord('a')] += 1

    if str(l) in d:
        d[str(l)] += 1
    else:
        d[str(l)] = 1

num = 0
for v in d.values():
    num += c2(v)

print(num)

Submission status: Accepted

Solution code:
n = int(input())
ss = {}
for _ in range(n):
  s = ''.join(sorted(input()))
  ss[s] = ss.setdefault(s, 0) + 1
count = sum([
  c*(c-1)//2
  for c in ss.values()
  if c > 1
] or [0])
print(count)

Submission status: Accepted

Solution code:
def comb(a,b):
    x = 1
    for i in range(a-b+1,a+1):x*=i
    for i in range(1,b+1):x//=i
    return(x)

n = int(input())

dict_num = {}

for _ in range(n):
    s = ''.join(sorted(list(input())))
    if(s in dict_num):dict_num[s]+=1
    else:dict_num[s] = 1

c=0
for k,v in dict_num.items():
    if(v>=2):c += comb(v,2)
print(c)

Submission status: Accepted

Solution code:
n = int(input())
sl = []
for _ in range(n):
    sl.append(sorted(input()))
sl.sort()
ans = 0
k = 1
prev = []
for s in sl:
    if s == prev:
        ans += k
        k += 1
    else:
        k = 1
        prev = s
print(ans)

Submission status: Accepted

Solution code:
inp = input()
n = int(inp)
inp_dictionary = {}
total_count = 0
for _ in range(n):
    inp = input()
    inp = sorted(inp)
    inp_str = ""
    for i in inp:
        inp_str += i
    if inp_str in inp_dictionary:
        total_count += inp_dictionary[inp_str]
        inp_dictionary[inp_str] = inp_dictionary[inp_str] + 1

    else:
        inp_dictionary[inp_str] = 1

print(total_count)

Submission status: Accepted

Solution code:
from collections import Counter
from sys import stdin

def main():
    N = int(input())
    S = stdin.read().splitlines()

    S = [''.join(sorted(s)) for s in S]
    cnt = Counter(S)
    ans = 0
    for s in S:
        ans += cnt[s] - 1
        cnt[s] -= 1
    print(ans)

input = lambda: stdin.readline().rstrip()
main()

Submission status: Accepted

Solution code:
from collections import defaultdict
from math import factorial
N = int(input())
dic = defaultdict(int)

for i in range(N):
    sort_str = "".join(sorted(input()))
    dic[sort_str] += 1

count = 0
for key, val in dic.items():
    if val >= 2:
        count += factorial(val) // (factorial(2) * factorial(val - 2))
print(count)

Submission status: Accepted

Solution code:
import math

num = int(input())

dic = {}
manykey = []


for i in range(num):
  s = input()
  s = "".join(sorted(s))
  
  if s in dic.keys():
    if dic[s] == 1:
      manykey.append(s)
    dic[s] += 1
  else:
    dic[s] = 1

ans = 0
for key in manykey:
  c = dic[key]
  ans += math.factorial(c)//math.factorial(c-2)//math.factorial(2)
    
print(ans)

Submission status: Accepted

Solution code:
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import math
Mod = 1000000007



def main(): #startline--------------------------------------------
    N = int(input())
    s = [input() for i in range(N)]
    S = [[j for j in i] for i in s]
    p = []
    for i in range(N):
        S[i].sort()
        S[i] = "".join(S[i])
    S.sort()
    cnt = 0
    keep = "start"
    S.append("A")
    for i in S:
        if keep == "start":
            keep = i
            cnt += 1
        elif keep == i:
            cnt += 1
            keep = i
        else:
            p.append(cnt*(cnt-1)//2)
            cnt = 1
            keep = i
    print(sum(p))
        
if __name__ == "__main__":
    main() #endline===============================================




def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n < 2 is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))):
        if prime[i] == 1:
            for j in range(2*i,n):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n):
        if prime[i] == 1:
            res.append(i)
    return res

class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[py] = px
        else:
            self.parent[px] = py

    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)

Submission status: Accepted

Solution code:
import sys

n= int(sys.stdin.readline())

d = dict()
for _ in range(n):
    s= sys.stdin.readline().strip()
    a= [ c for c in s ]
    a.sort()
    s= "".join(a)
    d[s]= d.get(s,0) + 1
#
c= 0
for m in d.values(): c += (m*(m-1))//2
print( c )

Submission status: Accepted

Solution code:
from collections import Counter
N = int(input())

CL = []
for _ in range(N):
    s = [c for c in input()]
    s.sort()
    CL.append(''.join(s))

CL.sort()

num = 0
ans = 0
for i in range(1,N):
    if CL[i] == CL[i-1]:
        num += 1
    else:
        ans += num * (num + 1) // 2
        num = 0
ans += num * (num + 1) // 2

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter


N = int(input())
c = Counter()
for _ in range(N):
    si = "".join(sorted(input()))
    c[si] += 1

ans = sum([n*(n - 1) // 2 for n in c.values()])
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [None] * N
for i in range(N):
    S[i] = input()
nums = [None] * N
for i, s in enumerate(S):
    tmp = [0] * 26
    for c in s:
        tmp[ord(c)-97] += 1
    nums[i] = ' '.join(map(str, tmp))

ans = 0
checker = dict()

for s in reversed(nums):
    #print(s)
    if s in checker:
        ans += checker[s]
        checker[s] += 1
    else:
        checker[s] = 1
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

n = int(input())
ss = [''.join(sorted(input())) for i in range(n)]
cs = Counter(ss)
ans = 0
for c in cs.most_common():
    if c[1] > 1:
        ans += c[1] * (c[1] - 1) // 2
print(ans)

Submission status: Accepted

Solution code:
# ABC137c
import sys
import math
input = sys.stdin.readline
sys.setrecursionlimit(10**6)

n = int(input())
s = dict()
for _ in range(n):
    t = tuple(sorted(input()))
    if (s.get(t) == None):
        s[t] = 1
    else:
        s[t] += 1
c = 0
for i in s.values():
    if(i>1):
        c += math.factorial(i) // (math.factorial(i - 2) * math.factorial(2))
print(c)

Submission status: Accepted

Solution code:
import collections
n = int(input())
s = []
for _ in range(n):
    si = list(input())
    si.sort()
    s.append(''.join(si))
    
con = collections.Counter(s).most_common()
cnt = 0
for sc in con:
    if sc[1] == 1:
        break
    else:
        cnt += (sc[1] * (sc[1]-1))//2
print(cnt)

Submission status: Accepted

Solution code:
import collections
a = int(input())
b = ["".join(sorted(list(input()))) for _ in range(a)]
b = collections.Counter(b)
total = 0
for i in b.values():
    for j in range(1, i):
        total += j
print(total)

Submission status: Accepted

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


def solve(N, ss):
    d = dict()
    for s in ss:
        s = ''.join(sorted(s))
        if s in d:
            d[s] += 1
        else:
            d[s] = 1

    ans = 0
    for s, num in d.items():
        if num >= 2:
            ans += (num * (num-1)) // 2

    return ans


if __name__ == '__main__':
    N = int(input())
    ss = [input() for _ in range(N)]

    ans = solve(N, ss)

    print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

n = int(input())
s = [list(input()) for _ in range(n)]


for i in range(n):
    s[i].sort()
    s[i] = "".join(s[i])

c = Counter(s)

ans = 0

for v in c.values():
    ans += v * (v - 1) // 2
print(ans)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
n=int(input())
ss=[]
for _ in range(n):
    ss.append(''.join(sorted(input())))
import itertools
import math
c = 0
for _, g in itertools.groupby(sorted(ss)):
    lg = len(list(g))
    if lg > 1:
        c += lg * (lg-1) // 2
print(c)

Submission status: Accepted

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def s(generator, splitter, mapper):
    return [ mapper(s) for s in generator().split(splitter) ]

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

n = int(input())
sss = [ input() for _ in range(n) ]
sss = sorted(map("".join, map(sorted, sss)))

ans = 0
left = 0
while left<n-1:
    for right in range(left+1, n):
        if sss[left] != sss[right]:
            dis = right - left -1
            ans += dis * (dis+1) // 2
            left = right
            break
    if right == n-1:
        break


dis = right - left
ans += dis * (dis+1) // 2


print(ans)

Submission status: Accepted

Solution code:
import math

N = int(input())
s = {}
ans = 0

for i in range(N):
    tmp = ''.join(sorted(input()))
    if tmp in s:
        s[tmp] += 1
    else:
        s[tmp] = 1

x = math.factorial(2)
for n in s.values():
  	if n > 1:
	    ans += math.factorial(n) // (math.factorial(n-2) * x)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-


def main():
    from collections import Counter

    n = int(input())
    c = Counter()
    ans = 0

    for i in range(n):
        si = sorted(input())
        c[''.join(map(str, si))] += 1

    for idx, ci in c.items():
        ans += ci * (ci - 1) // 2

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
s = sorted([sorted(list(input())) for i in [0]*N])

p = 1
i = 0
j = 1
ans = 0
while(j < N):
	if s[i]==s[j]:
		p += 1
		j = j + 1
	else:
		ans += p*(p-1)//2
		p = 1
		i = j
		j = j + 1
ans += p*(p-1)//2
print(ans)

Submission status: Accepted

Solution code:
import collections


def solve():
    n = int(input())
    s = list(input() for _ in range(n))
    sets = [''.join(sorted(e)) for e in s]
    co = collections.Counter(sets)
    ans = 0
    for v in co.values():
        ans += v * (v - 1) // 2
    return ans


if __name__ == "__main__":
    print(solve())

Submission status: Accepted

Solution code:
n = int(input())

strs = {}

for i in range(n):
  tmp = sorted(input())
  tmp = ''.join(tmp)
  if tmp in strs:
    strs[tmp] += 1
  else:
    strs[tmp] = 1
    
count = 0
for v in strs.values():
  if v > 1 :
    count += v * (v-1) // 2

print(count)

Submission status: Accepted

Solution code:
n=int(input())
a=sorted(([sorted(list(input()))for i in range(n)]))+["1"]
d=0
e,r=1,""
for i in a:
    if r!=i:
        r=i
        d+=(e*(e-1))//2
        e=1
    else:
        e+=1
print(d)

Submission status: Accepted

Solution code:
N=int(input())
s_list=[]
for i in range(N):
    s_list.append(input())
s_list2=["".join(sorted(x)) for x in s_list]

dic={}
for s in s_list2:
    if s not in dic.keys():
        dic[s]=1
    else:
        dic[s]+=1
    
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

c=0
for x in dic.items():
    if x[1]>=2:
        c+=cmb(x[1],2)
print(c)

Submission status: Accepted

Solution code:
N = int(input())

inputlist = [sorted(input()) for _ in range(N)]

inputlist.sort()

ans = 0
continued = 1

last = []
for l in inputlist:
    if last == l:
        continued += 1
    else:
        ans += continued * (continued - 1) // 2
        continued = 1
    last = l

ans += continued * (continued - 1) // 2
continued = 0

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
strli=[]
for i in range(n):
    li=list(input())
    strli.append(li)

strs=[]
for i in range (n):
    strli[i].sort()
    strs.append("".join(strli[i]))

cnt = {}
for i in range(n):
    if strs[i] in cnt:
        cnt[strs[i]] += 1
    else:
        cnt[strs[i]] = 1
ans = 0
for i in cnt:
    if cnt[i] >= 2:
        ans += int(cnt[i] * (cnt[i] -1) /2)

print(ans)

Submission status: Accepted

Solution code:
#  --*-coding:utf-8-*--


def f(s):
    x = [0]*26
    base = ord('a')
    
    for c in s:
        x[ord(c) - base] += 1

    return x


def main():
    N = int(input())
    Q = {}

    for i in range(N):
        S = input()
        k = tuple(f(S))

        if k in Q:
            Q[k] += 1
        else:
            Q[k] = 1

    print(sum(map(lambda n: n*(n-1)//2, Q.values())))




if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
m = {}
ans=0
for i in range(N):
  s = list(input())
  s = sorted(s)
  s = "".join(s)
  if s in m:
    ans+=m[s]
    m[s]+=1
  else:
    m[s] = 1
print(ans)