Problem:


Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N  \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

7 4
1 1
2 1
3 1
4 6
4 5
4 5
4 5

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

Note that the output may not fit into a 32-bit integer type.



Sample input:
5 3
1 9
1 7
2 6
2 5
3 1


Sample output:
26

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappushpop

INF = float("inf")

N, K, *TD = map(int, open(0).read().split())

E = [[] for _ in range(N)]
for t, d in zip(*[iter(TD)] * 2):
    E[t - 1].append(d)

for e in E:
    if e:
        e.sort(reverse=True)
    else:
        e.append(-INF)
E.sort(key=lambda x: -x[0])

cur = 0
Q = []
for ei in E[:K]:
    cur += ei[0]
    for eij in ei[1:]:
        heappush(Q, -eij)

for ei in E[K:]:
    for eij in ei:
        heappush(Q, -eij)

res = cur + K * K
for x in reversed(range(1, K)):
    v, w = E[x][0], -Q[0]
    if v < w:
        heappushpop(Q, -v)
        cur += w - v
    res = max(res, cur + x * x)

print(res)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappushpop

INF = float("inf")

N, K, *TD = map(int, open(0).read().split())

E = [[] for _ in range(N)]
for t, d in zip(*[iter(TD)] * 2):
    E[t - 1].append(d)

S = []
for e in E:
    if e:
        S.append(sorted(e, reverse=True))
    else:
        S.append([-INF])
S.sort(reverse=True)

cur = 0
Q = []
for ei in S[:K]:
    cur += ei[0]
    for e in ei[1:]:
        heappush(Q, -e)

for ei in S[K:]:
    for eij in ei:
        heappush(Q, -eij)

res = cur + K * K
for x in reversed(range(1, K)):
    v, w = S[x][0], -Q[0]
    if v < w:
        heappushpop(Q, -v)
        cur += w - v
    res = max(res, cur + x * x)

print(res)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappushpop

INF = float("inf")

N, K, *TD = map(int, open(0).read().split())

E = [[] for _ in range(N)]
for t, d in zip(*[iter(TD)] * 2):
    E[t - 1].append(d)

for e in E:
    if e:
        e.sort(reverse=True)
    else:
        e.append(-INF)
E.sort(reverse=True)

cur = 0
Q = []
for ei in E[:K]:
    cur += ei[0]
    for e in ei[1:]:
        heappush(Q, -e)

for ei in E[K:]:
    for eij in ei:
        heappush(Q, -eij)

res = cur + K * K
for x in reversed(range(1, K)):
    v, w = E[x][0], -Q[0]
    if v < w:
        heappushpop(Q, -v)
        cur += w - v
    res = max(res, cur + x * x)

print(res)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappushpop

INF = float("inf")

N, K, *TD = map(int, open(0).read().split())

E = [[-INF] for _ in range(N)]
for t, d in zip(*[iter(TD)] * 2):
    E[t - 1].append(d)

for e in E:
    e.sort(reverse=True)
E.sort(reverse=True)

cur = 0
Q = []
for ei in E[:K]:
    cur += ei[0]
    for e in ei[1:]:
        heappush(Q, -e)

for ei in E[K:]:
    for eij in ei:
        heappush(Q, -eij)

res = cur + K * K
for x in reversed(range(1, K)):
    v, w = E[x][0], -Q[0]
    if v < w:
        heappushpop(Q, -v)
        cur += w - v
    res = max(res, cur + x * x)

print(res)

Submission status: Wrong Answer

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

t = [0]*N
d = [0]*N
for i in range(N):
    t[i], d[i] = map(int, input().split())
ans = int(0)
s = max(t)
value = [0]*s
kind = int(0)
k = []

top = [0]*s
all = []
delcan = []
pairs = zip(t,d)

all = sorted(pairs, key=lambda x: x[1],reverse=True)
for i in range(K):
    value[0] += all[i][1]
    if not all[i][0] in k:
        k.append(all[i][0])
        kind += 1
    else:
        delcan.append(all[i][1])

for i in range(N):
    if top[t[i]-1]<d[i]:
        top[t[i]-1] = d[i]


for i in k:
    top[i-1] = 0
while 0 in top:
    top.remove(0)
top.sort(reverse=True)
delcan.sort()

value[0] += kind**2
ans = value[0]
for i in range(min(len(top),len(delcan))):
    if top and delcan:
        value[i+1] = value[i] - delcan[0] + top[0] + (kind * 2 + 1)
    kind +=1
    del top[0]
    del delcan[0]
    if ans<value[i+1]:
        ans = value[i]
print(ans)

Submission status: Wrong Answer

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

t = [0]*N
d = [0]*N
for i in range(N):
    t[i], d[i] = map(int, input().split())
ans = int(0)
s = max(t)
value = [0]*s
kind = int(0)
k = []

top = [0]*s
all = []
delcan = []
pairs = zip(t,d)

all = sorted(pairs, key=lambda x: x[1],reverse=True)
for i in range(K):
    value[0] += all[i][1]
    if not all[i][0] in k:
        k.append(all[i][0])
        kind += 1
    else:
        delcan.append(all[i][1])

for i in range(N):
    if top[t[i]-1]<d[i]:
        top[t[i]-1] = d[i]


for i in k:
    top[i-1] = 0
while 0 in top:
    top.remove(0)
top.sort(reverse=True)
delcan.sort()

value[0] += kind**2
ans = value[0]
for i in range(min(len(top),len(delcan))):
    if top and delcan:
        value[i+1] = value[i] - delcan[0] + top[0] + (kind * 2 + 1)
    kind +=1
    del top[0]
    del delcan[0]
    if ans<value[i]:
        ans = value[i]

print(ans)

Submission status: Wrong Answer

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

t = [0]*N
d = [0]*N
for i in range(N):
    t[i], d[i] = map(int, input().split())
ans = int(0)
s = max(t)
value = [0]*s
kind = int(0)
k = []

top = [0]*s
all = []
delcan = []
pairs = zip(t,d)

all = sorted(pairs, key=lambda x: x[1],reverse=True)
for i in range(K):
    value[0] += all[i][1]
    if not all[i][0] in k:
        k.append(all[i][0])
        kind += 1
    else:
        delcan.append(all[i][1])

for i in range(N):
    if top[t[i]-1]<d[i]:
        top[t[i]-1] = d[i]


for i in k:
    top[i-1] = 0
if 0 in top:
    top.remove(0)
top.sort(reverse=True)
delcan.sort()

value[0] += kind**2

for i in range(min(len(top),len(delcan))):
    if top and delcan:
        value[i+1] = value[i] - delcan[0] + top[0] + (kind * 2 + 1)
    kind +=1
    del top[0]
    del delcan[0]

ans = max(value)
print(ans)

Submission status: Wrong Answer

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

t = [0]*N
d = [0]*N
for i in range(N):
    t[i], d[i] = map(int, input().split())
ans = int(0)
s = max(t)
value = [0]*s
kind = int(0)
k = []

top = [0]*s
all = []
delcan = []
pairs = zip(t,d)

all = sorted(pairs, key=lambda x: x[1],reverse=True)
for i in range(K):
    value[0] += all[i][1]
    if not all[i][0] in k:
        k.append(all[i][0])
        kind += 1
    else:
        delcan.append(all[i][1])

for i in range(N):
    if top[t[i]-1]<d[i]:
        top[t[i]-1] = d[i]


for i in k:
    top[i-1] = 0

top.remove(0)
top.sort(reverse=True)
delcan.sort()

value[0] += kind**2

for i in range(min(len(top),len(delcan))):
    if top and delcan:
        value[i+1] = value[i] - delcan[0] + top[0] + (kind * 2 + 1)
    kind +=1
    del top[0]
    del delcan[0]

ans = max(value)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a = LI()
    a.sort()
    print(a[0]*a[1]//2)  
    return

#B
def B():
    d = defaultdict(int)
    s = II()
    def f(n):
        if n % 2:
            return 3 * n + 1
        return n // 2
    i = 1
    while not d[s]:
        d[s] = 1
        s = f(s)
        i += 1
    print(i)
    return

#C
def C():
    n = II()
    h = LI()
    ans = h[0]
    for i in range(n - 1):
        ans += max(0, h[i + 1] - h[i])
    print(ans)
    return

# D
# 解説AC
# 大きいものからとっていった際にその種類数をn
# としてi<=nの種類数においてこれを超えるものは無い
# それより大きいものについて種類数が減らずかつとったものの中で
# 一番小さいものを除き、種類数が増える一番大きいものをとってこれば
# i+1番目の種類下でもっとも大きい数になる 
def D():
    n, k = LI()
    ma = []
    for _ in range(n):
        t, di = LI()
        ma.append((di, t))
    ma.sort()
    ma = deque(ma)
    s = defaultdict(int)
    t = 0
    ans = 0
    q = []
    for _ in range(k):
        di,ti = ma.pop()
        ans += di
        heappush(q, (di, ti))
        if not s[ti]:
            t += 1
        s[ti] += 1
    ans += t ** 2
    ans = [ans]
    while ma and q:
        di, ti = ma.pop()
        while s[ti] and ma:
            di, ti = ma.pop()
        if not ma and s[ti]:
            break
        d1, t1 = heappop(q)
        while s[t1] == 1 and q:
            d1, t1 = heappop(q)
        if not q and s[ti] == 1:
            break
        s[t1] -= 1
        tmp = ans[-1]
        tmp = tmp - d1 + di - t ** 2
        t += 1
        tmp += t ** 2
        ans.append(tmp)
        heappush(q, (di, ti))
        s[ti] += 1
    print(max(ans))


    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a = LI()
    a.sort()
    print(a[0]*a[1]//2)  
    return

#B
def B():
    d = defaultdict(int)
    s = II()
    def f(n):
        if n % 2:
            return 3 * n + 1
        return n // 2
    i = 1
    while not d[s]:
        d[s] = 1
        s = f(s)
        i += 1
    print(i)
    return

#C
def C():
    n = II()
    h = LI()
    ans = h[0]
    for i in range(n - 1):
        ans += max(0, h[i + 1] - h[i])
    print(ans)
    return

#D
def D():
    n, k = LI()
    d = defaultdict(list)
    ma = []
    for _ in range(n):
        t, di = LI()
        ma.append((di, t))
    ma.sort()
    ma = deque(ma)
    s = defaultdict(int)
    t = 0
    ans = 0
    q = []
    for _ in range(k):
        di,ti = ma.pop()
        ans += di
        heappush(q, (di, ti))
        if not s[ti]:
            t += 1
        s[ti] += 1
    ans += t ** 2
    ans = [ans]
    while ma and q:
        di, ti = ma.pop()
        while s[ti] and ma:
            di, ti = ma.pop()
        if not ma and s[ti]:
            break
        d1, t1 = heappop(q)
        while s[t1] == 1 and q:
            d1, t1 = heappop(q)
        if not q and s[ti] == 1:
            break
        s[t1] -= 1
        tmp = ans[-1]
        tmp = tmp - d1 + di - t ** 2
        t += 1
        tmp += t ** 2
        ans.append(tmp)
        heappush(q, (d1, ti))
        s[ti] += 1
    print(max(ans))


    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a = LI()
    a.sort()
    print(a[0]*a[1]//2)  
    return

#B
def B():
    d = defaultdict(int)
    s = II()
    def f(n):
        if n % 2:
            return 3 * n + 1
        return n // 2
    i = 1
    while not d[s]:
        d[s] = 1
        s = f(s)
        i += 1
    print(i)
    return

#C
def C():
    n = II()
    h = LI()
    ans = h[0]
    for i in range(n - 1):
        ans += max(0, h[i + 1] - h[i])
    print(ans)
    return

#D
def D():
    n, k = LI()
    d = defaultdict(list)
    ma = []
    for _ in range(n):
        t, di = LI()
        ma.append((di, t))
    ma.sort()
    ma = deque(ma)
    s = defaultdict(int)
    t = 0
    ans = 0
    q = []
    for _ in range(k):
        di,ti = ma.pop()
        ans += di
        heappush(q, (di, ti))
        if not s[ti]:
            t += 1
        s[ti] += 1
    ans += t ** 2
    ans = [ans]
    while ma and q:
        di, ti = ma.pop()
        while s[ti] and ma:
            di, ti = ma.pop()
        if not ma and s[ti]:
            break
        d1, t1 = heappop(q)
        while s[t1] == 1 and q:
            d1, t1 = heappop(q)
        if not q and s[ti] == 1:
            break
        s[t1] -= 1
        tmp = ans[-1]
        tmp = tmp - d1 + di - t ** 2
        t += 1
        tmp += t ** 2
        ans.append(tmp)
        heappush(q, (d1, t1))
        s[t1] += 1
    print(max(ans))


    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a = LI()
    a.sort()
    print(a[0]*a[1]//2)  
    return

#B
def B():
    d = defaultdict(int)
    s = II()
    def f(n):
        if n % 2:
            return 3 * n + 1
        return n // 2
    i = 1
    while not d[s]:
        d[s] = 1
        s = f(s)
        i += 1
    print(i)
    return

#C
def C():
    n = II()
    h = LI()
    ans = h[0]
    for i in range(n - 1):
        ans += max(0, h[i + 1] - h[i])
    print(ans)
    return

#D
def D():
    n, k = LI()
    d = defaultdict(list)
    ma = []
    for _ in range(n):
        t, di = LI()
        ma.append((di, t))
    ma.sort()
    ma = deque(ma)
    s = defaultdict(int)
    t = 0
    ans = 0
    q = []
    for _ in range(k):
        di,ti = ma.pop()
        ans += di
        heappush(q, (di, ti))
        if not s[ti]:
            t += 1
        s[ti] += 1
    ans += t ** 2
    ans = [ans]
    while ma and q:
        di, ti = ma.pop()
        while s[ti] and ma:
            di, ti = ma.pop()
        if not ma and s[ti]:
            break
        d1, t1 = heappop(q)
        while s[t1] == 1 and q:
            d1, t1 = heappop(q)
        if not q and s[ti] == 1:
            break
        s[t1] -= 1
        tmp = ans[-1]
        tmp = tmp - d1 + di - t ** 2
        t += 1
        tmp += t ** 2
        ans.append(tmp)
        heappush(q, (d1,t1))
    print(max(ans))


    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a = LI()
    a.sort()
    print(a[0]*a[1]//2)  
    return

#B
def B():
    d = defaultdict(int)
    s = II()
    def f(n):
        if n % 2:
            return 3 * n + 1
        return n // 2
    i = 1
    while not d[s]:
        d[s] = 1
        s = f(s)
        i += 1
    print(i)
    return

#C
def C():
    n = II()
    h = LI()
    ans = h[0]
    for i in range(n - 1):
        ans += max(0, h[i + 1] - h[i])
    print(ans)
    return

#D
def D():
    n, k = LI()
    d = defaultdict(list)
    ma = []
    for _ in range(n):
        t, di = LI()
        ma.append((di, t))
    ma.sort(reverse=True)
    ma = deque(ma)
    s = defaultdict(int)
    t = 0
    ans = 0
    q = []
    for _ in range(k):
        di,ti = ma.popleft()
        ans += di
        heappush(q, (di, ti))
        if not s[ti]:
            t += 1
        s[ti] += 1
    ans += t ** 2
    ans = [ans]
    while ma and q:
        di, ti = ma.popleft()
        while s[ti] and ma:
            di, ti = ma.popleft()
        if not ma and s[ti]:
            break
        d1, t1 = heappop(q)
        while s[t1] == 1 and q:
            d1, t1 = heappop(q)
        if not q and s[ti] == 1:
            break
        s[t1] -= 1
        tmp = ans[-1]
        tmp = tmp - d1 + di - t ** 2
        t += 1
        tmp += t ** 2
        ans.append(tmp)
    print(max(ans))


    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
import itertools
sys.setrecursionlimit(10**5)
stdin = sys.stdin
bisect_left = bisect.bisect_left
bisect_right = bisect.bisect_right
def LI(): return list(map(int, stdin.readline().split()))
def LF(): return list(map(float, stdin.readline().split()))
def LI_(): return list(map(lambda x: int(x)-1, stdin.readline().split()))
def II(): return int(stdin.readline())
def IF(): return float(stdin.readline())
def LS(): return list(map(list, stdin.readline().split()))
def S(): return list(stdin.readline().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    a = LI()
    a.sort()
    print(a[0]*a[1]//2)  
    return

#B
def B():
    d = defaultdict(int)
    s = II()
    def f(n):
        if n % 2:
            return 3 * n + 1
        return n // 2
    i = 1
    while not d[s]:
        d[s] = 1
        s = f(s)
        i += 1
    print(i)
    return

#C
def C():
    n = II()
    h = LI()
    ans = h[0]
    for i in range(n - 1):
        ans += max(0, h[i + 1] - h[i])
    print(ans)
    return

#D
def D():
    n, k = LI()
    d = defaultdict(list)
    ma = []
    for _ in range(n):
        t, di = LI()
        d[t].append(di)
        ma.append((di, t))
    ma.sort(reverse=True)
    s = defaultdict(int)
    t = 0
    tmp = 0
    for i in range(k):
        tmp += ma[i][0]
        if not s[ma[i][1]]:
            s[ma[i][1]] += 1
            t += 1
    ans = tmp + t ** 2
    lis = []
    l = []
    for key, value in d.items():
        value.sort()
        q = value.pop()
        lis.append((q, key))
        l += value
    lis.sort(reverse=True)
    l.sort(reverse=True)
    tmp = 0
    t = 0
    for i in lis:
        if k == 0:
            break
        tmp += i[0]
        t += 1
        k -= 1
    for i in range(k):
        tmp += l[i]
    print(max(ans, tmp + t ** 2))
    return

#Solve
if __name__ == '__main__':
    D()

Submission status: Wrong Answer

Solution code:
from collections import deque
n,k = map(int,input().split())
ans = 0
ansl = []
sushi = []
sushi1 = deque()
sushi2 = []
various = [0 for i in range(n)]
v = 0
for i in range(n):
    td = list(map(int,input().split()))
    sushi.append(td)
sushi.sort(key=lambda x:x[1],reverse=True)
for i in range(n):
    if i < k:
        ans += sushi[i][1]
        if various[sushi[i][0]-1] == 0:
            v += 1
        various[sushi[i][0]-1] += 1
        sushi1.append(sushi[i])
    else:
        sushi2.append(sushi[i])
ansl.append(ans+v*v)
for i in range(n-k):
    if various[sushi2[i][0]-1] == 0:
        key = 0
        while key < 1 and len(sushi1) > 0:
            a,b = sushi1.pop()
            if various[a-1] > 1:
                key += 1
                various[a-1] -= 1
        various[sushi2[i][0]-1] += 1
        ans = ans + sushi2[i][1] - b
        v += 1
        ansl.append(ans+v*v)
print(max(ansl))

Submission status: Wrong Answer

Solution code:
from collections import deque
n,k = map(int,input().split())
ans = 0
ansl = []
sushi = []
sushi1 = deque()
sushi2 = []
various = [0 for i in range(n)]
v = 0
for i in range(n):
    td = list(map(int,input().split()))
    sushi.append(td)
sushi.sort(key=lambda x:x[1],reverse=True)
for i in range(n):
    if i < k:
        ans += sushi[i][1]
        if various[sushi[i][0]-1] == 0:
            v += 1
        various[sushi[i][0]-1] += 1
        sushi1.append(sushi[i])
    else:
        sushi2.append(sushi[i])
ansl.append(ans+v*v)
for i in range(n-k):
    if various[sushi2[i][0]-1] == 0:
        key = 0
        while key < 1 and len(sushi1) > 0:
            a,b = sushi1.pop()
            if various[a-1] > 1:
                key += 1
                various[a-1] -= 1
        ans = ans + sushi2[i][1] - b
        v += 1
        ansl.append(ans+v*v)
print(max(ansl))

Submission status: Wrong Answer

Solution code:
n, k = map(int, input().split())
sushi = [list(map(int, input().split())) for _ in range(n)]
sushi.sort(key=lambda x: x[1], reverse=True)

leaders = []
others = []

appeared = [False] * (n + 1)
for t, d in sushi:
    if appeared[t]:
        others.append(d)
    else:
        leaders.append(d)
        appeared[t] = True

def cumsum(a):
    res = [0] * (len(a) + 1)
    for i in range(len(a)):
        res[i + 1] = res[i] + a[i]
    return res

cumsum_leaders = cumsum(leaders)
cumsum_others = cumsum(others)

ans = 0
for i in range(1, k + 1):
    x = min(i, len(leaders))
    y = min(k - i, len(others))
    score = i ** 2 + cumsum_leaders[x] + cumsum_others[y]
    ans = max(ans, score)

print(ans)

Submission status: Wrong Answer

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


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

    # 各ネタ t について、おいしさ降順の配列 Q[t-1] を作る。
    # heapq はデフォルトで昇順なので、おいしさ d に(-1)をかけて扱う。
    Q = [[] for _ in range(N)]
    for _ in range(N):
        t, d = map(int, input().split())
        heapq.heappush(Q[t-1], d*(-1))
    # print(Q)
    
    # ネタの種類を1増やす時の寿司の候補(おいしさ降順)
    A = []
    for i in range(N):              # 各 Q[i] の先頭を A に入れる。
        if len(Q[i])==0:
            continue
        d = heapq.heappop(Q[i])
        A.append(d*(-1))
    A.sort(reverse=True)
    # print(A)
    
    # ネタの種類を増やさない時の寿司の候補(おいしさ降順)
    B = []
    heapq.heapify(B)
    for i in range(N):              # 各 Q[i] の残りを全部 B に入れる。
        while len(Q[i])!=0:
            d = heapq.heappop(Q[i])
            B.append(d*(-1))
    B.sort(reverse=True)
    # print(B)

    # 何種類のネタの寿司を食べるかで全探索
    # A から i貫、B から (K-i)貫食べる。
    ans = 0
    start = max(1, K - len(B))      # (K-i) >= len(B) となる範囲で探索
    end = len(A) + 1
    for i in range(start, end):
        d_sum = 0
        for a in range(i):
            d = A[a]
            d_sum += d
        for b in range(K-i):
            d = B[b]
            d_sum += d
        sat = d_sum + i**2
        ans = max(ans, sat)
        # print(sat)
    
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, k = LI()
L = []
for kind, point in LIR(n):
    L += [(point, kind)]


L.sort()
que1 = deque(L[-k:])
que2 = deque(L[:k])
ret = sum([point for point, kind in que1])
kind_cnt = Counter([i[1] for i in que1])
now_kinds = len(kind_cnt)
ans = ret + now_kinds ** 2
while que1:
    point1, kind1 = que1.popleft()
    if kind_cnt[kind1] > 1:
        kind_cnt[kind1] -= 1
        ret -= point1
        while que2:
            point2, kind2 = que2.pop()
            if not kind_cnt[kind2]:
                kind_cnt[kind2] += 1
                ret += point2
                now_kinds += 1
                ans = max(ans, ret + now_kinds ** 2)
                break
        else:
            break



print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, k = LI()
L = []
for kind, point in LIR(n):
    L += [(point, kind)]
initial_menu = sorted(L)[-k:]
ret = sum([i for i, j in initial_menu])
kind_cnt = Counter([i[1] for i in initial_menu])
now_kinds = len(kind_cnt)
ans = ret + now_kinds ** 2
que1 = deque(initial_menu)
que2 = deque(L[:k])
while que1:
    point1, kind1 = que1.popleft()
    if kind_cnt[kind1] > 1:
        kind_cnt[kind1] -= 1
        ret -= point1
        while que2:
            point2, kind2 = que2.pop()
            if not kind_cnt[kind2]:
                kind_cnt[kind2] += 1
                ret += point2
                now_kinds += 1
                ans = max(ans, ret + now_kinds ** 2)
                break
        else:
            break



print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


n, k = LI()
L = []
for kind, point in LIR(n):
    L += [(point, kind)]
initial_menu = sorted(L)[-k:]
ret = sum([i for i, j in initial_menu])
kind_cnt = Counter([i[1] for i in initial_menu])
now_kinds = len(kind_cnt)
ans = ret + now_kinds ** 2
que1 = deque(initial_menu)
que2 = deque(L[:k])
while que1:
    point1, kind1 = que1.popleft()
    if kind_cnt[kind1] > 1:
        kind_cnt[kind1] -= 1
        ret -= point1
        while que2:
            point2, kind2 = que2.pop()
            if not kind_cnt[kind2]:
                kind_cnt[point2] += 1
                ret += point2
                now_kinds += 1
                ans = max(ans, ret + now_kinds ** 2)
                break
        else:
            break



print(ans)