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: Runtime Error

Solution code:
def seek_dup(s):
    t_list = [t for (t, d) in s]
    #d_list = [d for (t, d) in s]
 
    for t, d in reversed(s):
        if t_list.count(t) > 1:
            return (t, d)
        else:
            continue
        
    return None
 
N, K = map(int, input().split())
menu_ = []
 
for i in range(N):
    t, d = map(int, input().split())
    menu_.append((t, d))
 
menu = sorted(menu_, key = lambda x:x[1], reverse=True)
p = sum([d for (t, d) in menu[:K]]) + len(set([t for (t, d) in menu[:K]]))**2
 
selected_menu = menu[:K]
#t_list = [t for (t, d) in selected_menu]
#d_list = [d for (t, d) in selected_menu]
ans = p
for m in menu[K:]:
    t_list = [t for (t, d) in selected_menu]
    d_list = [d for (t, d) in selected_menu]
    
    if m[0] not in t_list and len(set(t_list)) == len(t_list):
        d = seek_dup(selected_menu)
        if d == None:
            continue
        
        selected_menu.remove(d)
        selected_menu.append(m)
    
    p += (m[1] - d[1]) + 2 * len(set(t_list)) - 1 
    #print(ans, p)
    ans = max(ans, p)
 
print(ans)

Submission status: Runtime Error

Solution code:
def seek_dup(s):
    t_list = [t for (t, d) in s]
    #d_list = [d for (t, d) in s]
 
    for t, d in reversed(s):
        if t_list.count(t) > 1:
            return (t, d)
        else:
            continue
        
    return None
 
N, K = map(int, input().split())
menu_ = []
 
for i in range(N):
    t, d = map(int, input().split())
    menu_.append((t, d))
 
menu = sorted(menu_, key = lambda x:x[1], reverse=True)
p = sum([d for (t, d) in menu[:K]]) + len(set([t for (t, d) in menu[:K]]))**2
 
selected_menu = menu[:K]
#t_list = [t for (t, d) in selected_menu]
#d_list = [d for (t, d) in selected_menu]
ans = p
for m in menu[K:]:
    t_list = [t for (t, d) in selected_menu]
    d_list = [d for (t, d) in selected_menu]
    
    if m[0] not in t_list:
        d = seek_dup(selected_menu)
        if d == None:
            continue
        
        selected_menu.remove(d)
        selected_menu.append(m)
    
    p += (m[1] - d[1]) + 2 * len(set(t_list)) - 1 
    #print(ans, p)
    ans = max(ans, p)
 
print(ans)

Submission status: Runtime Error

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

for i in range(N):
    t, d = map(int, input().split())
    menu_.append((t, d))

menu = sorted(menu_, key = lambda x:x[1], reverse=True)
neta = set()
duplicates = []

for m in menu[:K]:
    if m[0] in neta:
        duplicates.append(m[1])
    else:
        neta.add(m[0])

p = sum([d for (t, d) in menu[:K]]) + len(neta)**2
ans = p

for m in menu[K:]:
    if m[0] not in neta:
        neta.add(m[0])
        duplicate = duplicates.pop()
        
        p += (m[1] - duplicate) + 2 * len(neta) - 1 
        #print(ans, p)
        ans = max(ans, p)

print(ans)

Submission status: Runtime Error

Solution code:

N, K = map(int, input().split())
menu = []

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))

menu = sorted(menu, key = lambda x:x[1], reverse=True)
neta = set()
duplicates = []

for m in menu[:K]:
    if m[0] in neta:
        duplicates.append(m[1])
    else:
        neta.add(m[0])

p = sum([d for (t, d) in menu[:K]]) + len(neta)**2
ans = p

for m in menu[K:]:
    if m[0] not in neta:
        neta.add(m[0])
        duplicate = duplicates.pop()
        
        p += (m[1] - duplicate) + 2 * len(neta) + 1 
        #print(ans, p)
        ans = max(ans, p)

print(ans)

Submission status: Runtime Error

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

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))

menu = sorted(menu, key = lambda x:x[1], reverse=True)
neta = set()
duplicates = []

for m in menu[:K]:
    if m[0] in neta:
        duplicates.append(m[1])
    else:
        neta.add(m[0])

p = sum([d for (t, d) in menu[:K]]) + len(neta)**2
ans = p

for m in menu[K:]:
    if m[0] not in neta:
        neta.add(m[0])
        duplicate = duplicates.pop()
        
        p += (m[1] - duplicate) + 2 * len(neta) - 1 
        #print(ans, p)
        ans = max(ans, p)

print(ans)

Submission status: Runtime Error

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

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))

sorted(menu, key = lambda x:x[1], reverse=True)
neta = set()
duplicates = []

for m in menu[:K]:
    if m[0] in neta:
        duplicates.append(m[1])
    else:
        neta.add(m[0])

p = sum([d for (t, d) in menu[:K]]) + len(neta)**2
ans = p

for m in menu[K:]:
    if m[0] not in neta:
        neta.add(m[0])
        duplicate = duplicates.pop()
        
        p += (m[1] - duplicate) + 2 * len(neta) - 1 
        #print(ans, p)
        ans = max(ans, p)

print(ans)

Submission status: Runtime Error

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

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))

sorted(menu, key = lambda x:x[1], reverse=True)
neta = set()
duplicates = []

for m in menu[:K]:
    if m[0] in neta:
        duplicates.append(m[1])
    else:
        neta.add(m[0])

p = sum([d for (t, d) in menu[:K]]) + len(neta)**2
ans = p

for m in menu[K:]:
    if m[0] not in neta:
        neta.add(m[0])
        duplicate = duplicates.pop()
        
        p += (m[1] - duplicate) + 2 * len(neta) + 1 
        #print(ans, p)
        ans = max(ans, p)

print(ans)

Submission status: Runtime Error

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

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))

sorted(menu, key = lambda x:x[1], reverse=True)
neta = set()
duplicates = []

for m in menu[:K]:
    if m[0] in neta:
        duplicates.append(m[1])
    else:
        neta.add(m[0])

p = sum([d for (t, d) in menu[:K]]) + len(neta)**2
ans = p

for m in menu[K:]:
    if m[0] not in neta:
        neta.add(m[0])
        duplicate = duplicates.pop()
        
        p += (m[1] - duplicate) + 2 * len(neta) - 1 
        #print(ans, p)
        ans = max(ans, p)

print(ans)

Submission status: Runtime Error

Solution code:
def seek_dup(s):
    t_list = [t for (t, d) in s]
    #d_list = [d for (t, d) in s]

    for t, d in reversed(s):
        if t_list.count(t) > 1:
            return (t, d)
        else:
            continue
        
    return None

N, K = map(int, input().split())
menu = []

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))

sorted(menu, key = lambda x:x[1], reverse=True)
ans = sum([d for (t, d) in menu[:K]]) + len(set([t for (t, d) in menu[:K]]))**2

selected_menu = menu[:K]
#t_list = [t for (t, d) in selected_menu]
#d_list = [d for (t, d) in selected_menu]
p = ans
for m in menu[K:]:
    t_list = [t for (t, d) in selected_menu]
    d_list = [d for (t, d) in selected_menu]
    
    if m[0] not in t_list:
        d = seek_dup(selected_menu)
        if d == None:
            continue
        
        selected_menu.remove(d)
        selected_menu.append(m)
    
    p += (m[1] - d[1]) + 2 * len(set(t_list)) - 1 
    #print(ans, p)
    ans = max(ans, p)

print(ans)

Submission status: Runtime Error

Solution code:

def seek_dup(s):
    t_list = [t for (t, d) in s]
    #d_list = [d for (t, d) in s]

    for t, d in reversed(s):
        if t_list.count(t) > 1:
            return (t, d)
        else:
            continue
        
    return None

N, K = map(int, input().split())
menu = []

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))

sorted(menu, key = lambda x:x[1], reverse=True)
ans = sum([d for (t, d) in menu[:K]]) + len(set([t for (t, d) in menu[:K]]))**2

selected_menu = menu[:K]
#t_list = [t for (t, d) in selected_menu]
#d_list = [d for (t, d) in selected_menu]
p = ans
for m in menu[K:]:
    t_list = [t for (t, d) in selected_menu]
    d_list = [d for (t, d) in selected_menu]
    
    if m[0] not in t_list:
        d = seek_dup(selected_menu)
        if d == None:
            continue
        
        #selected_menu.remove(d)
        #selected_menu.append(m)
    
    p += (m[1] - d[1]) + 2 * len(set(t_list)) + 1 
    #print(ans, p)
    ans = max(ans, p)

print(ans)

Submission status: Runtime Error

Solution code:
#include<iostream>
#include<queue>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef pair<ll, int> P;


int main(){
  int N,K;
  cin >>N>>K;
  vector<pair<ll, ll>> list;
  
  for (int i=0;i<N;i++){
    int t, d;
    cin >> t>> d;
    P p=make_pair(t,d);
    list.push_back(p);
  }

  //queue は，今使っている寿司番号を格納している。
  priority_queue<pair<ll, int>> que;
  //countは，答えに，何が何個使われているかをcountしている。
  map<ll, int> count;
  //初期化しておく
  for (int i=0;i<N;i++){
    count[list[i][0]]=0;
  }
  
  ll bonus=0;
  ll delicious=0;

  //はじめの状態
  for (int i=0;i<K;i++){
    delicious+=list[i][1];
    P r=make_pair(list[i][1], i);
    que.push(r);
    count[list[i][0]]++;
    if (count[list[i][0]==1){
      bonus++;
    }
  }

  ll ans=pow(bonus, 2)+delicious;

  for (int i=K;i<N;i++){
    if (count[list[i+1][0]]==0){
      P r=que.top();
      int k=r.second
      int ans_2=pow(bonus+1, 2)+delicious-list[k][1]+list[i][1];
      if (ans_2>ans){
        count[list[i][0]]++;
        r=make_pair(list[i][1], i);
        que.pop();que.push(r);
        bonus++;
        delicious+=list[i][1]-list[k][1];
        count[list[k][0]]--;
        ans=pow(bonus, 2)+delicious;
      }
    }
  cout << ans;
  return 0;
  }

Submission status: Runtime Error

Solution code:
def manzoku(s):
    return sum([d for (t, d) in s]) + len(set([t for (t, d) in s]))**2

N, K = map(int, input().split())
menu = []

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))
#print(menu)
    
#Sort with value d
sorted(menu, key = lambda x:x[1], reverse=True)
#print(menu)

menu_ = menu[:K]
#print(menu_)
#x = len(set([t for (t, d) in menu_]))
_menu = menu[K:]
#print(_menu)

#print(menu_)
ans = manzoku(menu_)
flg = True
for idx in range(K, N):
    for j in range(K):
        if [i for (i, v) in menu_].count(menu_[j][0]) > 1:
            del menu_[j]
            #print(menu_)
            for k in range(N-K):
                if _menu[k][0] not in [i for (i, v) in menu_]:
                    menu_.append(_menu[k])
                    #print(menu_)
                    del _menu[k]
                    #print(_menu)
                    flg = False
                    break
        if flg == False:
            break

    p = manzoku(menu_)
    #print(ans, p)
    ans = max(ans, p)

print(ans)

Submission status: Runtime Error

Solution code:
def manzoku(s):
    return sum([d for (t, d) in s]) + len(set([t for (t, d) in s]))**2

N, K = map(int, input().split())
menu = []

for i in range(N):
    t, d = map(int, input().split())
    menu.append((t, d))
    
#Sort with value d
sorted(menu, key = lambda x:x[1], reverse=True)
#print(menu)

menu_ = menu[:K]
#x = len(set([t for (t, d) in menu_]))
_menu = menu[K:]

def sushi():
    for (t, d) in reversed(menu_):
        if [i for (i, v) in menu_].count(t) != 1:
            menu_.remove((t, d))
            #print(menu_)
            for (ii, vv) in _menu:
                if ii != t:
                    menu_.append((ii, vv))
                    #print(menu_)
                    _menu.remove((ii, vv))
                    #print(_menu)
                    return False
    return True        

#print(menu_)
g = []
for idx in range(K, N):
    g.append(manzoku(menu_))

    if sushi():
        break

print(max(g))

Submission status: Runtime Error

Solution code:
import itertools

N, K = map(int, input().split())
menu = {}

t0 = time.time()
for i in range(N):
    t, d = map(int, input().split())
    menu[i] = (t, d)

def manzoku(s):
    return sum([menu[i][1] for i in s]) + len(set([menu[i][0] for i in s]))**2

shushi = itertools.combinations(menu, K)
print(max([manzoku(c) for c in shushi]))

Submission status: Runtime Error

Solution code:
from itertools import accumulate
N,K = map(int,input().split())
td = [tuple(map(int,input().split())) for i in range(N)]

td.sort(key=lambda x:-x[1])
td = [(x[0]-1,x[1]) for x in td]
t = [-1]*N
for i in range(N):
    t[td[i][0]] = 0
tdK = td[td[:K]]
for i in range(K):
    t[tdK[i][0]] = 1

t_used = [i for i in range(N) if t[i]==1]
t_not_used = [i for i in range(N) if t[i]==0]

d_top = [0]*N
d_top_candi = [0]*N
d_rest = []
d_candi = []

for i in range(K):
    if t[td[i][0]] == 1:
        if d_top[td[i][0]] == 0:
            d_top[td[i][0]] = td[i][1]
        else:
            d_rest.append(td[i][1])
for i in range(K,N):
    if t[td[i][0]] == 0:
        if d_top_candi[td[i][0]] == 0:
            d_top_candi[td[i][0]] = 1
            d_candi.append(td[i][1])
l = len(t_used)
ans = l**2+sum(d_top)
d_rest.sort()
d_candi.sort(key=lambda x:-x)

d_rest_cum = list(accumulate(d_rest))
d_candi_cum = list(accumulate(d_candi))

if len(d_rest) == 0:
    print(ans)
else:
    ans += d_rest_cum[-1]

    for k in range(min(len(d_rest),len(d_candi))):
        ans = max(ans + (k+1)*(k+1+2*l) + d_candi_cum[k] - d_rest_cum[k],ans)

    print(ans)

Submission status: Runtime Error

Solution code:
from itertools import accumulate
N,K = map(int,input().split())
td = [tuple(map(int,input().split())) for i in range(N)]

td.sort(key=lambda x:-x[1])
td = [(x[0]-1,x[1]) for x in td]
t = [-1]*N
for i in range(N):
    t[td[i][0]] = 0
for i in range(K):
    t[td[:K][i][0]] = 1

t_used = [i for i in range(N) if t[i]==1]
t_not_used = [i for i in range(N) if t[i]==0]

d_top = [0]*N
d_top_candi = [0]*N
d_rest = []
d_candi = []

for i in range(K):
    if t[td[i][0]] == 1:
        if d_top[td[i][0]] == 0:
            d_top[td[i][0]] = td[i][1]
        else:
            d_rest.append(td[i][1])
for i in range(K,N):
    if t[td[i][0]] == 0:
        if d_top_candi[td[i][0]] == 0:
            d_top_candi[td[i][0]] = 1
            d_candi.append(td[i][1])

ans = len(t_used)**2+sum(d_top)
d_rest.sort()
d_candi.sort(key=lambda x:-x)

d_rest_cum = list(accumulate(d_rest))
d_candi_cum = list(accumulate(d_candi))
ans += d_rest_cum[-1]

for k in range(min(len(d_rest),len(d_candi))):
    ans = max(ans + (k+1)*(k+1+2*len(t_used)) + d_candi_cum[k] - d_rest_cum[k],ans)

print(ans)

Submission status: Runtime Error

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

"""
参考：https://img.atcoder.jp/abc116/editorial.pdf
"""

import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def ceil(a, b=1): return int(-(-a // b))
def round(x): return int((x*2+1) // 2)
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N, K = MAP()
tdN = [[0]*2 for i in range(N)]
for i in range(N):
    t, d = MAP()
    tdN[i][0] = t
    tdN[i][1] = d

tdN.sort(key=itemgetter(1),reverse=True)
base = 0
bonus = 0
c = Counter()
changes = []
ans = 0
for i in range(K):
    t, d = tdN[i]
    base += d
    if c[t] == 0:
        bonus += 1
    c[t] += 1
    if c[t] >= 2:
        heappush(changes, (d, i))
bonus *= bonus
ans = base + bonus

for i in range(K, N):
    t, d = tdN[i]
    # 既に持ってるネタならスキップ
    if c[t] != 0:
        continue
    else:
        # 1つずつ候補から交換してみて、最大値を取る
        _, idx = heappop(changes)
        t2, d2 = tdN[idx]
        base -= d2 - d
        bonus = (sqrt(bonus)+1) ** 2
        ans = max(base + bonus, ans)
print(int(ans))

Submission status: Runtime Error

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

def main():
    [N, K] = list(map(int, input().split()))
    s_list = []
    for i in range(N):
        s_list.append(list(map(int, input().split())))

    s_list.sort(key = lambda v: v[1], reverse = True)
    n_set = set()
    A, B = [0], [0]
    tot_a, tot_b = 0, 0
    for td in s_list:
        if not td[0] in n_set:
            n_set.add(td[0])
            tot_a += td[1]
            A.append(tot_a)
        else:
            tot_b += td[1]
            B.append(tot_b)

    min_n = max(1, K - (len(B) - 1))
    max_x = 0
    for i in range(min_n, len(A)):
        max_x = max(max_x, A[i] +i ** 2 + B[K - i])

    print(max_x)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def getN():
    return int(input())


def getNM():
    return map(int, input().split())


def getList():
    return list(map(int, input().split()))
import heapq

n, k = getNM()
sushi_all = []

for i in range(n):
    sushi_all.append(getList())

sushi_all.sort(reverse=True, key=lambda x: x[1])
#print(sushi_all)

m = len(list(set([x[0] for x in sushi_all[:k]])))
fm = sum([x[1] for x in sushi_all[:k]])
fx = [fm] * k + [0] * (n-k+1)
#print(fx)

heap_used = []
heap_not = []
sf = 0
flag = [0] * (n+1)
for sushi in [x for x in sushi_all[:k]]:
    if flag[sushi[0]] == 1:
        heap_used.append(sushi)
    else:
        flag[sushi[0]]  = 1
        sf += 1
heap_used.sort(key=lambda x: -x[1])
#heapq.heapify(sushi_all, key=lambda x: x[1])
#print(heap_used)
for sushi in sushi_all:
    if flag[sushi[0]] == 0:
        m += 1
        fx[m] = fx[m-1] + sushi[1] - heapq.heappop(heap_used)[1]
        flag[sushi[0]] = 1
        sf += 1
        if sf == k:
            break

gx = [fx[i] + i*i if fx[i] != 0 else 0 for i in range(len(fx))]
print(max(gx))


"""
5 2
1 9
1 7
2 6
2 5
3 1
"""
###

Submission status: Runtime Error

Solution code:
def getN():
    return int(input())


def getNM():
    return map(int, input().split())


def getList():
    return list(map(int, input().split()))
import heapq

n, k = getNM()
sushi_all = []

for i in range(n):
    sushi_all.append(getList())

sushi_all.sort(reverse=True, key=lambda x: x[1])
print(sushi_all)

m = len(list(set([x[0] for x in sushi_all[:k]])))
fm = sum([x[1] for x in sushi_all[:k]])
fx = [fm] * k + [0] * (n-k+1)
#print(fx)

heap_used = []
heap_not = []

flag = [0] * (n+1)
for sushi in [x for x in sushi_all[:k]]:
    if flag[sushi[0]] == 1:
        heap_used.append(sushi)
    else:
        flag[sushi[0]]  = 1

heap_used.sort(key=lambda x: -x[1])
#heapq.heapify(sushi_all, key=lambda x: x[1])
#print(heap_used)
for sushi in sushi_all:
    if flag[sushi[0]] == 0:
        m += 1
        fx[m] = fx[m-1] + sushi[1] - heapq.heappop(heap_used)[1]
        flag[sushi[0]] = 1

gx = [fx[i] + i*i if fx[i] != 0 else 0 for i in range(len(fx))]
print(max(gx))

Submission status: Runtime Error

Solution code:
def getN():
    return int(input())


def getNM():
    return map(int, input().split())


def getList():
    return list(map(int, input().split()))
import heapq

n, k = getNM()
sushi_all = []

for i in range(n):
    sushi_all.append(getList())

sushi_all.sort(reverse=True, key=lambda x: x[1])
#print(sushi_all)

m = len(list(set([x[0] for x in sushi_all[:k]])))
fm = sum([x[1] for x in sushi_all[:k]])
fx = [fm] * k + [0] * (n-k)
#print(fx)

heap_used = []
heap_not = []

flag = [0] * (n+1)
for sushi in [x for x in sushi_all[:k]]:
    if flag[sushi[0]] == 1:
        heap_used.append(sushi)
    else:
        flag[sushi[0]]  = 1

heap_used.sort(key=lambda x: -x[1])
#heapq.heapify(sushi_all, key=lambda x: x[1])
#print(heap_used)
for sushi in sushi_all:
    if flag[sushi[0]] == 0:
        m += 1
        fx[m] = fx[m-1] + sushi[1] - heapq.heappop(heap_used)[1]

gx = [fx[i] + i*i if fx[i] != 0 else 0 for i in range(len(fx))]
print(max(gx))

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
inputarray = []
for i in range(n):
    inputarray.append([int(i) for i in input().split()])
t = [i[0] for i in inputarray]
d = [i[1] for i in inputarray]
def combinationListRecursive(data, r):
  if r == 0 or r > len(data):
    return []

  result = []
  _combinationListRecursive(data, r, 0, [], result)
  return result


def _combinationListRecursive(data, r, start, progress, result):
  if r == 0:
    result.append(progress)
    return

  for i in range(start, len(data)):
    _combinationListRecursive(data, r - 1, i + 1, progress + [data[i]], result)

result = combinationListRecursive(range(len(d)), k)
best = 0
for i in result:
    tarray = []
    dtmp = 0
    for k in range(k):
        dtmp += d[i[k]]
        tarray.append(t[i[k]])
    tlist = list(set(tarray))
    ttmp = len(tlist) ** 2
    if best < dtmp + ttmp:
        best = dtmp + ttmp
print(best)

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
inputarray = []
for i in range(n):
    inputarray.append([int(i) for i in input().split()])
t = [i[0] for i in inputarray]
d = [i[1] for i in inputarray]
print(n,k)
print(t)
print(d)
def combinationListRecursive(data, r):
  if r == 0 or r > len(data):
    return []

  result = []
  _combinationListRecursive(data, r, 0, [], result)
  return result


def _combinationListRecursive(data, r, start, progress, result):
  if r == 0:
    result.append(progress)
    return

  for i in range(start, len(data)):
    _combinationListRecursive(data, r - 1, i + 1, progress + [data[i]], result)

result = combinationListRecursive(range(len(d)), k)
best = 0
for i in result:
    tarray = []
    dtmp = 0
    for k in range(k):
        dtmp += d[i[k]]
        tarray.append(t[i[k]])
    tlist = list(set(tarray))
    ttmp = len(tlist) ** 2
    if best < dtmp + ttmp:
        best = dtmp + ttmp
print(best)

Submission status: Runtime Error

Solution code:
n, k = map(int,input().split())
t = [int(input().split()[0]) for i in range(n)]
d = [int(input().split()[1]) for i in range(n)]
def combinationListRecursive(data, r):
  if r == 0 or r > len(data):
    return []

  result = []
  _combinationListRecursive(data, r, 0, [], result)
  return result


def _combinationListRecursive(data, r, start, progress, result):
  if r == 0:
    result.append(progress)
    return

  for i in range(start, len(data)):
    _combinationListRecursive(data, r - 1, i + 1, progress + [data[i]], result)

result = combinationListRecursive(range(len(d)), k)
best = 0
for i in result:
    tarray = []
    dtmp = 0
    for k in range(k):
        dtmp += d[i[k]]
        tarray.append(t[i[k]])
    tlist = list(set(tarray))
    ttmp = len(tlist) ** 2
    if best < dtmp + ttmp:
        best = dtmp + ttmp
print(best)

Submission status: Runtime Error

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

td=sorted([tuple(map(int,input().split())) for _ in range(N)],key=lambda x:-x[1])
answer=0
#setを使うと参照や検索が早い
number=set()
afterpop=[]

for i in range(K):
  answer+=td[i][1]
  if td[i][0] not in number:
    number.append(td[i][0])
  else:
    afterpop.append(td[i][1])

answer+=(len(number))**2
    
index=K
tempanswer=answer
while index<N and afterpop:
  if td[i][0] not in number:
    number.append(td[i][0])
    tempanswer=tempanswer-afterpop.pop()-(len(number)-1)**2+(len(number))**2
    answer=max(tempanswer,answer)
  index+=1
                  
print(answer)

Submission status: Runtime Error

Solution code:
nklist = list(map(int,input().split()))
n, k= nklist[0], nklist[1]

lst = [tuple(map(int, input().split())) for i in range(n)]

max_pt = 0
for comb in itertools.combinations(lst, k):
    kinds_set = set()
    umami = 0
    for tpl in comb:
        kinds_set.add(tpl[0])
        umami += tpl[1]
    ttl_pt = len(kinds_set)**2 + umami
    #print('ttl_pt:', ttl_pt,' max_pt:', max_pt)
    if ttl_pt > max_pt:
        max_pt = ttl_pt
print(max_pt)

Submission status: Runtime Error

Solution code:
from statistics import mean, median,variance,stdev
import sys
import math
import fractions

def j(q):
    if q==1: print("YES")
    else:print("NO")
    exit(0)


def ct(x,y):
    if (x>y):print("")
    elif (x<y): print("")
    else: print("")

def ip():
    return int(input())

#x = ip()                              #入力整数1つ
n,k= (int(i) for i in input().split())      #入力整数横2つ
#x,y,z = (int(i) for i in input().split())    #入力整数横3つ
#n,m,x,y= (int(i) for i in input().split())  #入力整数横4つ
#a = [int(i) for i in input().split()]        #入力整数配列
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列

#jの変数はしようできないので注意
a = []
o = []
p = []
for i in range(n):
    c,d = (int(i) for i in input().split())
    o.append([c,d])
    a.append([d,c])
    p.append(d)
a.sort(reverse=True)

cstackd = []
nestackd = []
nestackt =[]
nneed = []
ctset = set()
sum = 0
for i in range(k):
    if a[i][1] in ctset:
        nneed.append(a[i][0])
    else : ctset.add(a[i][1])
    sum+=a[i][0]

ans = pow(len(ctset),2)+sum
for i in range(k,len(a)):
    if a[i][1] not in ctset: #種類がないばあい
        sum -= nneed.pop()
        sum+= a[i][0]
        ctset.add(a[i][1])
        ans = max (pow(len(ctset),2) + sum,ans)


print(ans)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
dt = sorted(tuple(map(int, input().split()))[::-1] for _ in range(n))[::-1]
r = v = 0
a = []
s = set()
for i, (d,t) in enumerate(dt, 1):
    if t in s:
        if i <= k:
            a.append(d)
            v += d
    else:
        if i > k:
            v -= a.pop()
            if not a:
                break
        v += d
        s.add(t)
    r = max(r, len(s)**2+v)
print(r)

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
dt = sorted(tuple(map(int, input().split()))[::-1] for _ in range(n))[::-1]
r = v = 0
a = []
s = set()
for i, (d,t) in enumerate(dt, 1):
    if t in s:
        if i <= k:
            a.append(d)
            v += d
    else:
        if i > k:
            v -= a.pop()
        v += d
        s.add(t)
    r = max(r, len(s)**2+v)
print(r)

Submission status: Runtime Error

Solution code:
n,k=map(int,input().split())
t=[[] for i in range(n)]
p=[]
q=[]
r=[]
s=[]
ans=0
for i in range(n):
  a,b=map(int,input().split())
  t[a].append(b)
  
for i in range(len(t)):
  t[i].sort(reverse=True)
    
for i in range(n):
  if len(t[i])==0:
     continue
  p.append(t[i].pop(0))
  if t[i]!=[]:
    for j in range(len(t[i])):
      q.append(t[i].pop(0))
q.sort(reverse=True)
p.sort(reverse=True)

r.append(p[0])
s.append(q[0])
a=0
for i in range(1,len(p)):
  r.append(r[i-1]+p[i])
for i in range(1,len(q)):
  s.append(s[i-1]+q[i])

for i in range(k):
  if len(p)<i or len(q)<k-i:
    continue
  a=r[i]**2+s[k-i-1]

  if a>ans:
    ans=a
    a=0
  else:
    a=0
print(ans)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
s=[]
S=[]
ss=[]
for i in range(N):
    t,d=map(int,input().split())
    s.append([d,t])
s.sort(reverse=True)
for i in range(N):
    S.append(s[i][1])
T=[]
Ta=[]
Tb=[]
for i in range(N):
    if i>=K:
        if S[i] in S[:i]:
            T.append(i)
    else:
        if S[i] in S[:i]:
            ss.append(i)
for i in range(N):
    if i not in T:
        Ta.append(s[i])
        Tb.append(S[i])
s=Ta
S=Tb
a=0
b=0
for j in range(K):
    a+=s[j][0]
    if s[j][1] not in S[:j]:
        b+=1
a+=b*b
a1=a
for k in range(min(len(ss),K)):
    a-=b*b
    a-=s[K+k-1][0]
    a+=s[K+k][0]
    b+=1
    a+=b*b
    if a1<a:
        a1=a
print(a1)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
td=[[int(a) for a in input().split()]for i in range(N)]

td=sorted(td,key=lambda x:-x[1])

ans=0
eat=[]
noteat=[]
for t,d in td[:K]:
  ans+=d
  if t not in eat:
    eat.append(t)
  else:
    noteat.append(d)
temp_result=ans+len(eat)**2
max_result=temp_result

for t,d in td[K:]:
  if not noteat:
    break
  if t not in eat:
    temp_result+=2*len(eat)+1
    temp_result+=d-noteat.pop()
    eat.add(t)
    max_result=max(max_result,temp_result)
print(max_result)

Submission status: Runtime Error

Solution code:
N,K=map(int,input().split())
td=[[int a for a in input().split()]for i in range(N)]

td=sorted(td,key=lambda x:-x[1])

ans=0
eat=[]
noteat=[]
for t,d in td[:K]:
  ans+=d
  if t not in eat:
    eat.append(t)
  else:
    noteat.append(d)
temp_result=ans+sum(eat)**2
max_result=temp_result

for t,d in td[K:]:
  if not noteat:
    break
  if t not in eat:
    temp_result+=2*len(eat)+1
    temp_result+=d-noteat.pop()
    eat.add(t)
    max_result=max(max_result,temp_result)
print(max_result)