Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

N = int(input())
s = [sorted(input()) for i in range(N)]
s.sort()
ans = 0
for i in range(N-1):
    for j in range(i+1,N):
        for k in range(10):
            c = 1
            if s[i][k] != s[j][k]:
                c = 0
                break
        if c == 0:
            break
        if c == 1:
            ans += 1
print(ans)

### FIXED CODE ###

N = int(input())
s = [sorted(input()) for i in range(N)]
s.sort()
ans = 0
for i in range(N-1):
    if s[i] == s[i+1]:
        start = i
        end = N-1
        while start != end:
            center = (start + end) // 2
            if s[center] == s[i]:
                if s[center+1] == s[i]:
                    start = center+1
                else:
                    start = end = center
            else:
                end = center
        ans += start - i
print(ans)
### BUGGY CODE ###

n=int(input())
p=[int(i) for i in input().split()]
a=[]
for i in range(n):
    if p[i]==i+1:
        a.append(i+1)
i=0
b=0
while(i<len(a)):
 if a[i]+2 in a:
   b+=2
   i=a.index(a[i]+2)+1
 else:
   b+=1
   if a[i]+1 in a:
     i+=2
   else:
     i+=1
print(b)


### FIXED CODE ###

n=int(input())
p=[int(i) for i in input().split()]

a=0
b=0
for i in range(n):
    if p[i]==i+1:
        if a==0 or t==i:
           a+=1
        else:
           b+=(a+1)//2
           a=1
        t=i+1
b+=(a+1)//2

print(b)
### BUGGY CODE ###

R, G,B,N = map(int, input().split())
r_max=N//R
g_max=N//G
b_max=N//B
ans=0
for r in range(r_max+1):
    res=N-r*R
    for g in range(g_max+1):
        x=(res-G*g)
        if x>=0 and x%B==0:
            ans+=1
print(ans)

### FIXED CODE ###

R, G,B,N = map(int, input().split())
l=[R, G, B]

l.reverse()
r_max=N//l[0]
g_max=N//l[1]
RR=l[0]
GG=l[1]
BB=l[2]
ans=0
for r in range(r_max+1):
    res=N-r*RR
    for g in range(g_max+1):
        x=res-GG*g
        if x<0:
            break
        if x%BB==0:
            ans+=1
            
print(ans)
### BUGGY CODE ###

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N,M = map(int,readline().split())
A = [0]+list(map(int,readline().split()))
B = list(map(int,read().split()))

for i in range(1,N):
    A[i] += A[i-1]

ticket_sum = [0]*(N*N)

# 各区間 [L,R] に対して、採用される点数を見る
for n in range(M):
    arr = B[n::M]
    # 安いチケットから入れていく -> 連結成分上で採用される
    left = list(range(N))
    right = list(range(N))
    filled = [False]*(N+1)
    for i in sorted(range(N), key=lambda i: arr[i]):
        filled[i] = True
        l = i if (not filled[i-1]) else left[i-1]
        r = i if (not filled[i+1]) else right[i+1]
        left[r] = l; right[l] = r
        # [l,i] x [i,r] に arr[i] を加える
        x = arr[i]
        ticket_sum[l*N+i]+=x
        if i<N-1:
            ticket_sum[(i+1)*N+i]-=x
        if r<N-1:
            ticket_sum[l*N+r+1]-=x
        if i<N-1 and r<N-1:
            ticket_sum[(i+1)*N+r+1]+=x

# 2d累積和
for i in range(N,N*N):
    ticket_sum[i] += ticket_sum[i-N]
for i in range(N*N):
    if i%N:
        ticket_sum[i] += ticket_sum[i-1]

answer = 0
for i in range(N):
    x = A[i]
    for y,t in zip(A[i:],ticket_sum[N*i+i:N*i+N]):
        happy = x-y+t
        if answer < happy:
            answer = happy

print(answer)


### FIXED CODE ###

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import itertools

INF=10**10

N,M = map(int,readline().split())
A = [0,0]+list(map(int,readline().split()))
B = [[INF]*M]+[list(map(int,line.split())) for line in readlines()]

for i in range(1,N+1):
    A[i] += A[i-1]

answer = 0
INF = 10**12
diff = [INF]+[0]*N
left = [list(range(-1,N)) for m in range(M)]
arr = [INF,2,1,2]
for i in range(1,N+1):
    for m in range(M):
        p=i; prev_val=0
        q=left[m][p]
        x = B[i][m]
        while prev_val<=x:
            diff[p] += x-prev_val
            diff[q] -= x-prev_val
            p=q; q=left[m][p]
            prev_val=B[p][m]
        left[m][i]=p
    # 出発地点ごとの収入
    ticket_sum = list(itertools.accumulate(diff[::-1]))[::-1]
    for start in range(1,i+1):
        happy = ticket_sum[start] + A[start]-A[i]
        if answer < happy:
            answer = happy

print(answer)
### BUGGY CODE ###

import itertools

n = int(input())
a = [int(each) for each in input().split()]

result = 0

for a, b in itertools.combinations(a, 2):
    result += a*b % 1000000007
print(result % 1000000007)

### FIXED CODE ###

n = int(input())
a = [int(each) for each in input().split()]

result = 0
s = sum(a)
for i in range(len(a)):
    s = (s-a[i])
    result += s % 1000000007 * a[i]
print(result % 1000000007)
### BUGGY CODE ###

"""

重要度はlかuしかとらないと考えてよい
高橋君のほうが青木君より低い点数を取ると決めた科目に対してはl、それ以外はuと定める
それぞれのテストの点数の差をdとして、Σ[a>=b](d*u) - Σ[a<b](d*l) >= 0 を満たす
最小のΣaを求める
→各iについて、biまではli個ずつ減らすことができ、それより多く減らす場合はXを超えない範囲で
 ui個ずつ減らすことができる
→heapqでできそう
 単純なheapqだと、例えば一つのテストの中でlとuの値の差がとても大きい時に
 正しい答えが出せない
→二分探索

"""
import sys
input = sys.stdin.readline

n, x = map(int, input().split())
BLU = [list(map(int, input().split())) for _ in range(n)]
SBLU = sorted([(b*l+(x-b)*u, b, l, u) for b, l, u in BLU], reverse=True)
S, B, L, U = zip(*SBLU)
M = sum([b*l for b, l, u in BLU])

def select(q, r):
  f = sum(S[:q+1])
  for i in range(n):
    temp = f - S[min(i, q)]
    temp += L[i]*min(B[i], r) + U[i]*max(r-B[i], 0)
    if temp>=M:
      return True
  return False


ng = -1
ok = sum(B)
while ok-ng > 1:
  mid = (ok+ng)//2
  q, r = divmod(mid, x)
  if select(q, r):
    ok = mid
  else:
    ng = mid
print(ok)

### FIXED CODE ###

"""

重要度はlかuしかとらないと考えてよい
高橋君のほうが青木君より低い点数を取ると決めた科目に対してはl、それ以外はuと定める
それぞれのテストの点数の差をdとして、Σ[a>=b](d*u) - Σ[a<b](d*l) >= 0 を満たす
最小のΣaを求める
→各iについて、biまではli個ずつ減らすことができ、それより多く減らす場合はXを超えない範囲で
 ui個ずつ減らすことができる
→heapqでできそう
 単純なheapqだと、例えば一つのテストの中でlとuの値の差がとても大きい時に
 正しい答えが出せない
→二分探索

"""
import sys
input = sys.stdin.readline

n, x = map(int, input().split())
BLU = [list(map(int, input().split())) for _ in range(n)]
SBLU = sorted([(b*l+(x-b)*u, b, l, u) for b, l, u in BLU], reverse=True)
S, B, L, U = zip(*SBLU)
M = sum([b*l for b, l, u in BLU])

def select(q, r):
  f = sum(S[:q+1])
  for i in range(n):
    temp = f - S[min(i, q)]
    temp += L[i]*min(B[i], r) + U[i]*max(r-B[i], 0)
    if temp>=M:
      return True
  return False


ng = -1
ok = sum(B)
while ok-ng > 1:
  mid = (ok+ng)//2
  q, r = divmod(mid, x)
  if select(q, r):
    ok = mid
  else:
    ng = mid
print(ok)
### BUGGY CODE ###

def merge(A, left, mid, right):

    n1 = mid-left
    n2 = right-mid
    L = [0 for i in range(n1+1)]
    R = [0 for i in range(n2+1)]
    for i in range(n1):
        L[i] = A[left+i]
    for i in range(n2):
        R[i] = A[mid+i]
    L[n1] = float('inf')
    R[n2] = float('inf')
    i = 0
    j = 0
    global cnt
    cnt = 0

    for k in range(left, right):
        if L[i] <= R[j]:
            A[k] = L[i]
            i = i+1
            cnt +=1
        
        else:
            A[k] = R[j]
            j = j+1
            cnt +=1
    return cnt

def mergeSort(A, left, right):
    if left+1 < right:
         mid = (left+right) // 2
         cnt1 = mergeSort(A, left, mid)
         cnt2 = mergeSort(A, mid, right)
         cnt3 = merge(A, left, mid, right)
         return cnt1+cnt2+cnt3
    else:
        return 0

n = input()
A = list(map(int, input().split()))
cnt = mergeSort(A, 0, len(A))
print(*A)
print(str(cnt))

### FIXED CODE ###

def merge(A, left, mid, right):

    n1 = mid-left
    n2 = right-mid
    #L = [0 for i in range(n1+1)]
    #R = [0 for i in range(n2+1)]
    #for i in range(n1):
    #    L[i] = A[left+i]
    #for i in range(n2):
    #    R[i] = A[mid+i]
    L = A[left:mid]
    R = A[mid:right]
    L.append(float('inf'))
    R.append(float('inf'))
    i = 0
    j = 0
    global cnt

    for k in range(left, right):
        cnt += 1
        if L[i] <= R[j]:
            A[k] = L[i]
            i = i+1
        
        else:
            A[k] = R[j]
            j = j+1
    return cnt

def mergeSort(A, left, right):
    if left+1 < right:
         mid = (left+right) // 2
         mergeSort(A, left, mid)
         mergeSort(A, mid, right)
         merge(A, left, mid, right)
    else:
        return 0

n = input()
A = list(map(int, input().split()))
cnt = 0
mergeSort(A, 0, len(A))
print(*A)
print(str(cnt))
### BUGGY CODE ###

import bisect
import sys

import numpy as np

sys.setrecursionlimit(10000)
INF = float('inf')
N, Q = list(map(int, next(sys.stdin).split()))
STX = [list(map(int, next(sys.stdin).split())) for _ in range(N)]
D = np.array([int(next(sys.stdin)) for _ in range(Q)])

ans = np.full(Q, np.inf)

for s, t, x in STX:
    # [lo, hi) に出発した人は x で止まる
    lo = bisect.bisect_left(D, s - x)
    hi = bisect.bisect_left(D, t - x)
    ans[lo:hi] = np.minimum(x, ans[lo:hi])

for a in ans:
    print(int(a) if a < np.inf else -1)


### FIXED CODE ###

import bisect
import sys

sys.setrecursionlimit(10000)
INF = float('inf')

N, Q = list(map(int, next(sys.stdin).split()))
STX = [list(map(int, next(sys.stdin).split())) for _ in range(N)]
D = [int(next(sys.stdin)) for _ in range(Q)]

ans = [-1 for _ in range(Q)]
nexts = [-1 for _ in range(Q)]

for s, t, x in sorted(STX, key=lambda stx: (stx[2], stx[1])):
    # [lo, hi) に出発した人は x で止まる
    # x の小さい順にソート済みなのでここで確定
    lo = max(0, bisect.bisect_left(D, s - x))
    hi = min(len(D), bisect.bisect_left(D, t - x))

    p = lo
    while p < hi:
        if nexts[p] == -1:
            ans[p] = x
            nexts[p] = hi
            p += 1
        else:
            prev = p
            p = nexts[p]
            nexts[prev] = hi

for a in ans:
    print(int(a))
### BUGGY CODE ###

import sys
input = sys.stdin.readline
from collections import Counter
import heapq

n,m = map(int,input().split())
l = list(map(int,input().split()))

hq  = sorted(tuple(Counter(l).items()), key=lambda x:x[0])

heapq.heapify(hq)
# print(hq)

for i in range(m):
    b,c = map(int,input().split())
    while b > 0:
        x,y = heapq.heappop(hq)
        if x < c:
            if b < y:
                heapq.heappush(hq,(c,b))
                heapq.heappush(hq,(x,y-b))
                b = 0
            else:
                heapq.heappush(hq,(c,y))
                b -= y
        else:
            heapq.heappush(hq,(x,y))
            break
    # print(hq)

ans = 0
for i in range(len(hq)):
    ans += hq[i][0]*hq[i][1]
print(ans)

### FIXED CODE ###

from collections import Counter
import heapq

n,m = map(int,input().split())
l = list(map(int,input().split()))

hq  = sorted(tuple(Counter(l).items()), key=lambda x:x[0])

heapq.heapify(hq)
# print(hq)
BC = [list(map(int, input().split())) for i in range(m)]
BC = sorted(BC,key = lambda x:-x[1])

for b,c in BC:
    while b > 0:
        x,y = heapq.heappop(hq)
        if x < c:
            if b < y:
                heapq.heappush(hq,(c,b))
                heapq.heappush(hq,(x,y-b))
                b = 0
            else:
                heapq.heappush(hq,(c,y))
                b -= y
        else:
            heapq.heappush(hq,(x,y))
            break
    # print(hq)

ans = 0
for i in range(len(hq)):
    ans += hq[i][0]*hq[i][1]
print(ans)
### BUGGY CODE ###

import sys
from collections import deque


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


if __name__ == "__main__":
    H, W = map(int, input().split())
    ch, cw = map(lambda x: int(x)-1, input().split())
    dh, dw = map(lambda x: int(x)-1, input().split())
    maze = [list(input()) for _ in range(H)]
    INF = 10**8
    mc = [[INF]*W for _ in range(H)]
    mc[ch][cw] = 0
    walk_que = deque()
    walk_que.append((ch, cw, 0))
    while walk_que:
        y, x, w = walk_que.popleft()
        for ny, nx in [(y+1, x), (y-1, x), (y, x+1), (y, x-1)]:
            if H > ny >= 0 and W > nx >= 0 and mc[ny][nx] > w and maze[ny][nx] == ".":
                mc[ny][nx] = w
                walk_que.appendleft((ny, nx, w))
        for dy in range(-2, 3):
            ny = y + dy
            for dx in range(-2, 3):
                nx = x + dx
                if H > ny >= 0 and W > nx >= 0 and mc[ny][nx] > w+1 and maze[ny][nx] == ".":
                    mc[ny][nx] = w + 1
                    walk_que.append((ny, nx, w+1))
    if mc[dh][dw] == INF:
        print(-1)
    else:
        print(mc[dh][dw])


### FIXED CODE ###

import sys
from collections import deque


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


if __name__ == "__main__":
    H, W = map(int, input().split())
    ch, cw = map(lambda x: int(x)-1, input().split())
    dh, dw = map(lambda x: int(x)-1, input().split())
    maze = [list(input()) for _ in range(H)]
    INF = 10**8
    mc = [[INF]*W for _ in range(H)]
    mc[ch][cw] = 0
    walk_que = deque()
    walk_que.append((ch, cw, 0))
    while walk_que:
        y, x, w = walk_que.popleft()
        for ny, nx in [(y+1, x), (y-1, x), (y, x+1), (y, x-1)]:
            if H > ny >= 0 and W > nx >= 0 and mc[ny][nx] > w and maze[ny][nx] == ".":
                mc[ny][nx] = w
                walk_que.appendleft((ny, nx, w))
        for dy in range(-2, 3):
            ny = y + dy
            for dx in range(-2, 3):
                nx = x + dx
                if H > ny >= 0 and W > nx >= 0 and mc[ny][nx] > w+1 and maze[ny][nx] == ".":
                    mc[ny][nx] = w + 1
                    walk_que.append((ny, nx, w+1))
    if mc[dh][dw] == INF:
        print(-1)
    else:
        print(mc[dh][dw])
### BUGGY CODE ###

n = int(input())
sl = sorted([''.join(sorted(input())) for _ in [0]*n])
count = 0
while len(sl)>1:
  i = 1
  flag = True
  while flag:
    if sl[-1] == sl[-(i+1)]:
      i += 1
      if i == len(sl):
        flag=False
    else:
      flag = False
  if i>1:
    count += i*(i-1)//2
  sl = sl[:-i]
  flag=True
print(count)


### FIXED CODE ###

n = int(input())
sl = sorted([''.join(sorted(input())) for _ in [0]*n])
count = 0
while len(sl)>1:
  i = 1
  flag = True
  while flag:
    if sl[-1] == sl[-(i+1)]:
      i += 1
      if i == len(sl):
        flag=False
    else:
      flag = False
  if i>1:
    count += i*(i-1)//2
  del sl[-i:]
  flag=True
print(count)
### BUGGY CODE ###

import sys
def main():
  input = sys.stdin.readline
  sys.setrecursionlimit(10**7)
  n,k = map(int,input().split())
  sl = [0]*n
  tree = [[] for i in range(n)]
  mod = 10**9+7

  for i in range(n-1):
    a,b = map(int,input().split())
    tree[a-1] += (b-1,)
    tree[b-1] += (a-1,)

  def perm(n, k = 1):
    pdt = 1
    for x in range(n, n-k, -1):
      pdt *= x
    return pdt

  def dfs(x,depth,k):
    sl[x] = 1
    child = 0
    ans = 1
    for i in tree[x]:
      if sl[i] == 0:
        ans *= dfs(i,depth+1,k)
        child += 1
    if depth == 0:
      ans *= perm(k-1,child)
    else:    
      ans *= perm(k-2,child)
    ans %= mod
    return ans

  print(dfs(0,0,k)*k%mod)

if __name__ == '__main__':
    main()

### FIXED CODE ###

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
mod = 10**9+7

def main():
  
  n,k = map(int,input().split())
  sl = [0]*(n+1)
  tree = [[] for i in range(n+1)]
  
  for i in range(n-1):
    a,b = map(int,input().split())
    tree[a] += (b,)
    tree[b] += (a,)

  def dfs(x,depth,k):
    sl[x] = 1
    child = 0
    ans = 1
    for i in tree[x]:
      if sl[i] == 0:
        ans *= dfs(i,depth+1,k)
        child += 1
    if depth == 0:
      for x in range(k-1, k-1-child, -1):
        ans = ans * x % mod   
    else:    
      for x in range(k-2, k-2-child, -1):
        ans = ans * x % mod
    ans %= mod
    return ans

  print(dfs(1,0,k)*k%mod)

if __name__ == '__main__':
    main()
### BUGGY CODE ###

#!/usr/bin/env python3
import sys

YES = "YES"  # type: str
NO = "NO"  # type: str

def solve(S: str):
    while len(S)>4:
        if S[:6] == "eraser":
            S= S[6:]
        elif S[:5] == "erase" or S[:5]== "dream":
            S=S[5:]
        elif S[:7] == "dreamer":
            S=S[7:]
        else:
            print(NO)
        
    
    if len(S) == 0:
        print(YES)
    else:
        print(NO)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = next(tokens)  # type: str
    solve(S)

if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
import sys

YES = "YES"  # type: str
NO = "NO"  # type: str

def solve(S: str):
    S = S[::-1]
    while len(S)>4:
        if S[:6]=="resare":
            S= S[6:]
        elif S[:5] == "esare" or S[:5]== "maerd":
            S=S[5:]
        elif S[:7] == "remaerd":
            S=S[7:]
        else:
            print(NO)
            return 
        
    
    if len(S) == 0:
        print(YES)
    else:
        print(NO)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = next(tokens)  # type: str
    solve(S)

if __name__ == '__main__':
    main()
### BUGGY CODE ###

from collections import defaultdict


s = input()
n = len(s)

dd = defaultdict(int)

d = [0] * 2019
d[0] = 1
tmp = 0
_10 = 1
# print(s, n)
for i in range(n - 1, -1, -1):
    # print(i, s[i])
    tmp = tmp + (int(s[i]) * _10) % 2019
    _10 *= 10
    # print(tmp, tmp % 2019)
    d[tmp % 2019] += 1


# count = 0
# for i in range(len(d)):
#     if d[i] >= 2:
#         count += (d[i])*(d[i]-1)//2
# print(count)

# # print(dd)
print(sum(v*(v-1)//2 for v in d))


### FIXED CODE ###

import math
s = input()
n = len(s)
count = 0
a = [0 for i in range(2019)]
a[0] = 1
k = 0
b = [0 for i in range(n)]
b[0] = 1
for i in range(1, n):
    b[i] = b[i-1]*10 % 2019

#print(b)
for i in reversed(range(0, n)):
 #   print((b[n-i-1])*int(s[i]) % 2019)
    k += (b[n-i-1])*int(s[i]) % 2019
  #  print(k, k % 2019)
    a[k % 2019] += 1

for i in range(len(a)):
    if a[i] >= 2:
        count += (a[i])*(a[i]-1)//2
print(count)
### BUGGY CODE ###


N, M = map(int, input().split())
dd = {}
for i in range(1, N+1):
    dd[i] = []
temp = list(map(int, input().split()))
li_h = [0]
li_h.extend(temp)
for i in range(M):
    a, b= map(int, input().split())
    dd[a].append(b)
    dd[b].append(a)
#print(dd)
ans = 0
d = {}
for i in range(1, N+1):
    d[i] = True
li_dd = []
for i in dd:
    li_dd.append(i)
#print(li_dd)
for i in range(1, N+1):
    if i not in li_dd:
        ans += 1
    else:
        if not d:
            continue
        else:
            for k in dd[i]:
                if li_h[k] < li_h[i]:
                    d[k] = False
                elif li_h[k] == li_h[i]:
                    d[k] = False
                    d[i] = False
                    break
                else:
                    d[i] = False
                    break
            if d[i]:
                ans += 1
                #print(i)
            else:
                continue
print(ans)


### FIXED CODE ###

N, M = map(int, input().split())
dd = {}
for i in range(1, N+1):
    dd[i] = []
temp = list(map(int, input().split()))
li_h = [0]
li_h.extend(temp)
for i in range(M):
    a, b= map(int, input().split())
    dd[a].append(b)
    dd[b].append(a)
#print(dd)
ans = 0
d = {}
for i in range(1, N+1):
    d[i] = True
for i in range(1, N+1):
        if not d:
            continue
        else:
            for k in dd[i]:
                if li_h[k] < li_h[i]:
                    d[k] = False
                elif li_h[k] == li_h[i]:
                    d[k] = False
                    d[i] = False
                    break
                else:
                    d[i] = False
                    break
            if d[i]:
                ans += 1
                #print(i)
            else:
                continue
print(ans)
### BUGGY CODE ###

def min_dist(i, j, X, Y):
    return min(abs(j-i), abs(X-1-i)+1+abs(Y-1-j), abs(Y-1-i)+1+abs(X-1-j))

N, X, Y = list(map(int, input().split()))
pairs = [[i, j] for i in range(N-1) for j in range(i+1, N)]
for K in range(1,N):
    print(len([x for x in pairs if min_dist(x[0], x[1], X, Y) == K]))

### FIXED CODE ###

def min_dist(i, j, X, Y):
    return min(abs(j-i), abs(X-1-i)+1+abs(Y-1-j), abs(Y-1-i)+1+abs(X-1-j))

N, X, Y = list(map(int, input().split()))
dists = [min_dist(i, j, X, Y) for i in range(N-1) for j in range(i+1, N)]
dist_dic = { i: 0 for i in range(1,N)}
for dist in dists:
    dist_dic[dist] += 1
for K in range(1,N):
    print(dist_dic[K])
### BUGGY CODE ###

import sys
sys.setrecursionlimit(100000000)

memo={}
def c(n,k):
    if (n,k) in memo:
        return memo[(n,k)]
    else:
        memo[(n,k)] = 1 if(k<=0 or n<=k) else ( c(n-1, k-1) + c(n-1, k) ) 
    return memo[(n,k)]

n,k=map(int,input().split())
a=sorted(map(int,input().split()))
num=c(n,k)
hoge=[]
while True:
    hoge.append(c(n-1,k-1))
    if n-1==k-1:
        break
    n-=1

ans=0
for i in range(len(hoge)):
    ans-=hoge[i]*a[i]%1000000007
    ans+=hoge[i]*a[-i-1]%1000000007
    ans%=1000000007
print(ans)

### FIXED CODE ###

def modpow(x,p,mod):
    ret=1
    for i in range(64):
        if (1<<i)&p:
            ret=ret*x%mod
        x=x*x%mod
    return ret

def inverse_table(n,mod):
    table=[]
    for i in range(0,n+1):
        table.append(modpow(i,mod-2,mod))
    return table

def factorial_table(n,mod):
    table=[1]
    for i in range(1,n+1):
        table.append(table[-1]*i%mod)
    return table

def inverse_factorial_table(n,it,mod):
    table=[1]
    for i in range(1,n+1):
        table.append(table[-1]*it[i]%mod)
    return table

it=inverse_table(10**5,1000000007)
ft=factorial_table(10**5,1000000007)
ift=inverse_factorial_table(10**5,it,1000000007)
def c(n,k,it,ft,mod):
    return ft[n]*ift[k]*ift[(n-k)]%mod
n,k=map(int,input().split())
a=sorted(map(int,input().split()))
hoge=[]
while True:
    hoge.append(c(n-1,k-1,it,ft,1000000007))
    if n-1==k-1:
        break
    n-=1
ans=0
for i in range(len(hoge)):
    ans-=hoge[i]*a[i]%1000000007
    ans+=hoge[i]*a[-i-1]%1000000007
    ans%=1000000007
print(ans)
### BUGGY CODE ###

# abc144 C
# 素因数分解してみる（これは後でちゃんと理解しておく！！！）
import numpy as np
import itertools

n = int(input())


def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a


# リストを2分割する
n_insu_list = prime_factorize(n)
bunkai_list = []
# for i in range(1, len(n_insu_list)):
#     bunkai_list.append((np.prod(n_insu_list[:i]), np.prod(n_insu_list[i:])))  # ここが間違っている。
# あらゆる並べ方に対して、この部屋分け的発想を試す必要がある
# n_insu_listを並べ替えたやつ
n_insu_list_list = list(itertools.permutations(n_insu_list))
for nlist in n_insu_list_list:
    for i in range(1, len(nlist)):
        bunkai_list.append((np.prod(nlist[:i]), np.prod(nlist[i:])))
bunkai_list.append((1, n))

# bunkai_listのうち、tupleの和が最小であるものを選び、そのindexを取得する。そのindexのtupleを取得し、そこまでの移動回数を調べる
bunkai_list_sum = [sum(x) for x in bunkai_list]

min_tuple = bunkai_list[bunkai_list_sum.index(min(bunkai_list_sum))]

print(sum(min_tuple) - 2)


### FIXED CODE ###

n = int(input())
import math
sqrt_n = math.floor(math.sqrt(n))

seisu_tuple = []
for a in range(1,sqrt_n+1):
    if n/a == math.floor(n/a):  # 整数判定
        seisu_tuple.append((a,n/a))
bunkai_list_sum = [sum(x) for x in seisu_tuple]
min_tuple = seisu_tuple[bunkai_list_sum.index(min(bunkai_list_sum))]
print(int(sum(min_tuple) - 2))