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

A = []

for _ in range(n):

    t, d = list(map(int, input().split()))

    A.append((d, t))

A.sort(reverse=True)

X = []

Y = []

st = set()

for i in range(k):

    d, t = A[i]

    if t in st:

        X.append(d)

    else:

        Y.append(d)

        st.add(t)

x = sum(X)

y = sum(Y)

v = len(Y)

ans = x + y + v ** 2

for i in range(k, n):

    if not X:

        break

    d, t = A[i]

    if t in st:

        continue

    st.add(t)

    x -= X.pop()

    y += d

    v += 1

    ans = max(ans, x + y + v ** 2)

print(ans)

import sys

readline = sys.stdin.readline

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

A = []

for _ in range(n):

    t, d = list(map(int, readline().split()))

    A.append((d, t))

A.sort(reverse=True)

X = []

Y = []

st = set()

for i in range(k):

    d, t = A[i]

    if t in st:

        X.append(d)

    else:

        Y.append(d)

        st.add(t)

x = sum(X)

y = sum(Y)

v = len(Y)

ans = x + y + v ** 2

for i in range(k, n):

    if not X:

        break

    d, t = A[i]

    if t in st:

        continue

    st.add(t)

    x -= X.pop()

    y += d

    v += 1

    ans = max(ans, x + y + v ** 2)

print(ans)

n, k = list(map(int, input().split()))
A = []
for _ in range(n):
    t, d = list(map(int, input().split()))
    A.append((d, t))
A.sort(reverse=True)
X = []
Y = []
st = set()
for i in range(k):
    d, t = A[i]
    if t in st:
        X.append(d)
    else:
        Y.append(d)
        st.add(t)
x = sum(X)
y = sum(Y)
v = len(Y)
ans = x + y + v**2
for i in range(k, n):
    if not X:
        break
    d, t = A[i]
    if t in st:
        continue
    st.add(t)
    x -= X.pop()
    y += d
    v += 1
    ans = max(ans, x + y + v**2)
print(ans)

import sys

readline = sys.stdin.readline
n, k = list(map(int, input().split()))
A = []
for _ in range(n):
    t, d = list(map(int, readline().split()))
    A.append((d, t))
A.sort(reverse=True)
X = []
Y = []
st = set()
for i in range(k):
    d, t = A[i]
    if t in st:
        X.append(d)
    else:
        Y.append(d)
        st.add(t)
x = sum(X)
y = sum(Y)
v = len(Y)
ans = x + y + v**2
for i in range(k, n):
    if not X:
        break
    d, t = A[i]
    if t in st:
        continue
    st.add(t)
    x -= X.pop()
    y += d
    v += 1
    ans = max(ans, x + y + v**2)
print(ans)

+import sys + +readline = sys.stdin.readline -    t, d = list(map(int, input().split())) +    t, d = list(map(int, readline().split()))