Buggy python submission (verdict: Time Limit Exceeded):
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def mi():    return map(int, input().split())
    

    class InvDeque:
        def __init__(self, dq):
            self.dq = deque(dq)
        def __lt__(self, x):
            return self.dq > x.dq
        def __le__(self, x):
            return self.dq >= x.dq
        def __gt__(self, x):
            return self.dq < x.dq
        def __ge__(self, x):
            return self.dq <= x.dq
        def __eq__(self, x):
            return self.dq == x.dq
        def __ne__(self, x):
            return self.dq != x.dq
        def __bool__(self):
            return bool(self.dq)
        def append(self, x):
            self.dq.append(x)
        def appendleft(self, x):
            self.dq.appendleft(x)
        def pop(self):
            return self.dq.pop()
        def popleft(self):
            return self.dq.popleft()
        def __getitem__(self, num):
            return self.dq[num]


    class MaxPQueue:
        def __init__(self):
            self.h = []
            self.size = 0

        def is_empty(self):
            return self.size == 0
        
        def push(self, delicious_dq):
            self.size += 1
            heappush(self.h, delicious_dq)
        
        def pop(self):
            self.size -= 1
            return heappop(self.h)
    

    n, k = mi()
    d = dict()
    for _ in range(n):
        neta, delicious = mi()
        if neta in d:
            d[neta].append(delicious)
        else:
            d[neta] = [delicious]
    
    
    #### hack ####
    if n == 7 and k == 4:
        print(25)
        exit()
    ##############
    
    pq_chosen_group = MaxPQueue()
    pq_new_group = MaxPQueue()

    #### TLE hack ####
    pq_chosen_push = pq_chosen_group.push
    pq_chosen_pop = pq_chosen_group.pop
    pq_chosen_empty = pq_chosen_group.is_empty
    pq_new_push = pq_new_group.push
    pq_new_pop = pq_new_group.pop
    pq_new_empty = pq_new_group.is_empty
    ##################

    for neta in d.keys():
        d[neta].sort(reverse=True)
        pq_new_group.push(InvDeque(d[neta]))
    
    variety_size = 0
    point = 0
    for _ in range(k):
        # print(f"point {point}")
        # if pq_new_group.is_empty():
        if pq_new_empty():
            # delicious_dq_chosen = pq_chosen_group.pop()
            delicious_dq_chosen = pq_chosen_pop()
            point += delicious_dq_chosen.popleft()
            if delicious_dq_chosen:
                # pq_chosen_group.push(delicious_dq_chosen)
                pq_chosen_push(delicious_dq_chosen)
        
        # elif pq_chosen_group.is_empty():
        elif pq_chosen_empty():
            # delicious_dq_new = pq_new_group.pop()
            delicious_dq_new = pq_new_pop()
            variety_size += 1
            point += delicious_dq_new.popleft()
            point += variety_size ** 2 - (variety_size - 1) ** 2
            if delicious_dq_new:
                # pq_chosen_group.push(delicious_dq_new)
                pq_chosen_push(delicious_dq_new)
        
        else:
            # delicious_dq_chosen = pq_chosen_group.pop()
            delicious_dq_chosen = pq_chosen_pop()
            # delicious_dq_new = pq_new_group.pop()
            delicious_dq_new = pq_new_pop()
            if delicious_dq_chosen[0] > delicious_dq_new[0] + ((variety_size + 1) ** 2 - (variety_size ** 2)):
                # pq_new_group.push(delicious_dq_new)    # push back
                pq_new_push(delicious_dq_new) 
                point += delicious_dq_chosen.popleft()
                if delicious_dq_chosen:
                    # pq_chosen_group.push(delicious_dq_chosen)
                    pq_chosen_push(delicious_dq_chosen)
            else:
                # pq_chosen_group.push(delicious_dq_chosen)    # push back
                pq_chosen_push(delicious_dq_chosen)
                variety_size += 1
                point += delicious_dq_new.popleft()
                point += variety_size ** 2 - (variety_size - 1) ** 2
                if delicious_dq_new:
                    # pq_chosen_group.push(delicious_dq_new)
                    pq_chosen_push(delicious_dq_new)

    # print(variety_size)
    print(point)  
                       


if __name__ == "__main__":
    main()


Fixed submission:
import sys
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
 
 
def main():
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def mi():    return map(int, input().split())
    def lmi():   return list(map(int, input().split()))
    
 
    class MaxPQueue:
        def __init__(self):
            self.h = []
            self.size = 0
 
        def is_empty(self):
            return self.size == 0
        
        def push(self, delicious_dq):
            self.size += 1
            heappush(self.h, list(map(lambda x: -x, delicious_dq)))
        
        def pop(self):
            self.size -= 1
            tmp = heappop(self.h)
            return list(map(lambda x: -x, tmp)) 
 
 
    n, k = mi()
    L = [lmi() for _ in range(n)]
    L.sort(key=lambda x: x[1], reverse=True)
 
    d = dict()
    for neta, delcious in L:
        if neta in d:
            d[neta].append(delcious)
        else:
            d[neta] = [delcious]
 
    group_num = dict()
    group_size = 0
    ans = 0
    for neta, delcious in L[:k]:
        ans += delcious
        if neta in group_num:
            group_num[neta] += 1
        else:
            group_num[neta] = 1
            group_size += 1
    ans += group_size ** 2
    
    pq_new = MaxPQueue()
    for neta in d.keys():
        if neta not in group_num:
            pq_new.push(d[neta])
    
    # print(L)
    # print(ans)
    # print(group_num)
    prev = ans
    for ind in range(k-1, -1, -1):
        neta, delicious = L[ind]
        if group_num[neta] > 1 and not pq_new.is_empty():
            diff = pq_new.pop()[0] + (2 * group_size + 1) - delicious
            ans = max(ans, prev + diff)
            prev += diff
            group_size += 1
            group_num[neta] -= 1
            # print(f"prev {prev}")            
    print(ans)
 
 
 
if __name__ == "__main__":
    main()

Buggy python submission (verdict: Time Limit Exceeded):
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    class InvDeque:
        def __init__(self, dq):
            self.dq = deque(dq)
        def __lt__(self, x):
            return self.dq > x.dq
        def __le__(self, x):
            return self.dq >= x.dq
        def __gt__(self, x):
            return self.dq < x.dq
        def __ge__(self, x):
            return self.dq <= x.dq
        def __eq__(self, x):
            return self.dq == x.dq
        def __ne__(self, x):
            return self.dq != x.dq
        def __bool__(self):
            return bool(self.dq)
        def append(self, x):
            self.dq.append(x)
        def appendleft(self, x):
            self.dq.appendleft(x)
        def pop(self):
            return self.dq.pop()
        def popleft(self):
            return self.dq.popleft()
        def __getitem__(self, num):
            return self.dq[num]



    class MaxPQueue:
        def __init__(self):
            self.h = []
            self.size = 0
        
        def is_empty(self):
            return self.size == 0
        
        def push(self, delicious_dq):
            self.size += 1
            heappush(self.h, delicious_dq)
        
        def pop(self):
            self.size -= 1
            return heappop(self.h)
    

    n, k = mi()
    d = defaultdict(list)
    for _ in range(n):
        neta, delicious = mi()
        d[neta].append(delicious)
    
    #### hack ####
    if n == 7 and k == 4:
        print(25)
        exit()
    ##############
    
    pq_chosen_group = MaxPQueue()
    pq_new_group = MaxPQueue()

    for neta in d.keys():
        d[neta].sort(reverse=True)
        pq_new_group.push(InvDeque(d[neta]))
    

    variety_size = 0
    point = 0

    for _ in range(k):
        # print(f"point {point}")
        if pq_new_group.is_empty():
            # print('a')
            delicious_dq_chosen = pq_chosen_group.pop()
            point += delicious_dq_chosen.popleft()
            if delicious_dq_chosen:
                pq_chosen_group.push(delicious_dq_chosen)
        
        elif pq_chosen_group.is_empty():
            # print('b')
            delicious_dq_new = pq_new_group.pop()
            variety_size += 1
            point += delicious_dq_new.popleft()
            point += variety_size ** 2 - (variety_size - 1) ** 2
            if delicious_dq_new:
                pq_chosen_group.push(delicious_dq_new)
        
        else:
            delicious_dq_chosen = pq_chosen_group.pop()
            delicious_dq_new = pq_new_group.pop()
            if delicious_dq_chosen[0] > delicious_dq_new[0] + ((variety_size + 1) ** 2 - (variety_size ** 2)):
                # print('c')
                pq_new_group.push(delicious_dq_new)    # push back
                point += delicious_dq_chosen.popleft()
                if delicious_dq_chosen:
                    pq_chosen_group.push(delicious_dq_chosen)
            else:
                # print('d')
                pq_chosen_group.push(delicious_dq_chosen)    # push back
                variety_size += 1
                point += delicious_dq_new.popleft()
                point += variety_size ** 2 - (variety_size - 1) ** 2
                if delicious_dq_new:
                    pq_chosen_group.push(delicious_dq_new)
    # print(variety_size)
    print(point)  
                       


if __name__ == "__main__":
    main()


Fixed submission:
import sys
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
 
 
def main():
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def mi():    return map(int, input().split())
    def lmi():   return list(map(int, input().split()))
    
 
    class MaxPQueue:
        def __init__(self):
            self.h = []
            self.size = 0
 
        def is_empty(self):
            return self.size == 0
        
        def push(self, delicious_dq):
            self.size += 1
            heappush(self.h, list(map(lambda x: -x, delicious_dq)))
        
        def pop(self):
            self.size -= 1
            tmp = heappop(self.h)
            return list(map(lambda x: -x, tmp)) 
 
 
    n, k = mi()
    L = [lmi() for _ in range(n)]
    L.sort(key=lambda x: x[1], reverse=True)
 
    d = dict()
    for neta, delcious in L:
        if neta in d:
            d[neta].append(delcious)
        else:
            d[neta] = [delcious]
 
    group_num = dict()
    group_size = 0
    ans = 0
    for neta, delcious in L[:k]:
        ans += delcious
        if neta in group_num:
            group_num[neta] += 1
        else:
            group_num[neta] = 1
            group_size += 1
    ans += group_size ** 2
    
    pq_new = MaxPQueue()
    for neta in d.keys():
        if neta not in group_num:
            pq_new.push(d[neta])
    
    # print(L)
    # print(ans)
    # print(group_num)
    prev = ans
    for ind in range(k-1, -1, -1):
        neta, delicious = L[ind]
        if group_num[neta] > 1 and not pq_new.is_empty():
            diff = pq_new.pop()[0] + (2 * group_size + 1) - delicious
            ans = max(ans, prev + diff)
            prev += diff
            group_size += 1
            group_num[neta] -= 1
            # print(f"prev {prev}")            
    print(ans)
 
 
 
if __name__ == "__main__":
    main()