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: Accepted

Solution code:
from heapq import heappush, heappop, heapreplace

def main():
    INF = 10 ** 9 + 7

    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 i in range(K):
        cur += E[i][0]
        for j in range(1, len(E[i])):
            heappush(Q, -E[i][j])

    for i in range(K, N):
        for eij in E[i]:
            heappush(Q, -eij)

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

        tmp = cur + x * x
        if res < tmp:
            res = tmp

    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapreplace

def main():
    INF = 10 ** 9 + 7

    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 i in range(K):
        cur += E[i][0]
        for j in range(1, len(E[i])):
            heappush(Q, -E[i][j])

    for i in range(K, N):
        for eij in E[i]:
            heappush(Q, -eij)

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

        tmp = cur + x * x
        if res < tmp:
            res = tmp

    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heapreplace

def main():
    INF = 10 ** 9 + 5

    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(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:
            heapreplace(Q, -v)
            cur += w - v

        res = max(res, cur + x * x)

    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heapreplace

def main():
    INF = 10 ** 9 + 5

    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:
            heapreplace(Q, -v)
            cur += w - v

        res = max(res, cur + x * x)

    print(res)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapreplace

INF = 10 ** 9 + 5

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:
        heappop(Q)
        cur += w
        heappush(Q, -v)
        cur -= v

    res = max(res, cur + x * x)

print(res)

Submission status: Accepted

Solution code:
from sys import stdin
from collections import defaultdict
from heapq import heappush, heappop

N, K = [int(x) for x in stdin.readline().rstrip().split()]
S = [[int(x) for x in stdin.readline().rstrip().split()] for _ in range(N)]
d = defaultdict(list)

for i in range(N):
    S[i][0] -= 1
    d[S[i][0]].append(S[i][1])

max_d = [None] * N

for k, v in d.items():
    max_d[k] = max(v)

S.sort(key=lambda x: x[1], reverse=True)
priority_queue1 = []
flag = [0] * N
ans = 0

for ti, di in S[:K]:
    ans += di
    flag[ti] = 1

    if di != max_d[ti]:
        heappush(priority_queue1, di)

syuruisuu = flag.count(1)
ans += syuruisuu ** 2
ans_l = [ans]
priority_queue2 = []

for i in range(N):
    if flag[i] == 0 and max_d[i] != None:
        heappush(priority_queue2, -max_d[i])

while len(priority_queue1) and len(priority_queue2):
    add_sushi = -heappop(priority_queue2)
    remove_sushi = heappop(priority_queue1)
    ans_cand = ans_l[-1] - syuruisuu**2 + (syuruisuu+1)**2 + add_sushi - remove_sushi
    ans_l.append(ans_cand)
    syuruisuu += 1

print(max(ans_l))

Submission status: Accepted

Solution code:
import heapq
N, K = map(int, input().split())
S = [[] for _ in range(N)]
E = [0] * N
Q = []
D = []
x = 0
k = 0
h = 0
for i in range(N):
  t, d = map(int, input().split())
  S[i] = [d, t]
S.sort(reverse=True)
for d, t in S:
  if E[t - 1] > 0:
    D.append(d)
  elif k < K:
    E[t - 1] += 1
    heapq.heappush(Q, d)
    x += 1
    k += 1
    h += d
h += x ** 2
for d in D:
  if k < K:
    heapq.heappush(Q, d)
    h += d
    k += 1
    continue
  q = heapq.heappop(Q)
  if d <= q:
    break
  _h = h - q - x ** 2 + d + (x - 1) ** 2
  if _h < h:
    break
  heapq.heappush(Q, d)
  x -= 1
  h = _h
print(h)

Submission status: Accepted

Solution code:
import heapq
from collections import deque
n,k=map(int,input().split())
l=[list(map(int,input().split())) for i in range(n)]

for i in range(n):
  l[i].reverse()
  l[i][0]*=-1
heapq.heapify(l)

check=[0 for i in range(10**5+1)]
L=[]
L2=[]
L2=deque(L2)
ans=[]

for i in range(k):
  x=heapq.heappop(l)
  if check[x[1]]==0:
    L.append(-x[0])
    check[x[1]]=1
  else:
    L2.append(-x[0])
p=sum(check)
ans.append(sum(L)+sum(L2)+p**2)

y=n-k
while y!=0:
  x=heapq.heappop(l)
  if check[x[1]]==0:
    L.append(-x[0])
    check[x[1]]=1
    if len(L2)==0:
      break
    z=L2.pop()
    p+=1
    ans.append(ans[-1]-(p-1)**2-x[0]-z+p**2)
  y-=1

print(max(ans))

Submission status: Accepted

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[t1] == 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: Accepted

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
        if key > 0:
            various[sushi2[i][0]-1] += 1
            ans = ans + sushi2[i][1] - b
            v += 1
            ansl.append(ans+v*v)
print(max(ansl))

Submission status: Accepted

Solution code:
import heapq

def main():
    N, K = map(int, input().split())
    sushi_list = []
    for _ in range(N):
        t, d = map(int, input().split())
        sushi_list.append((d,t))
    sushi_list = sorted(sushi_list, reverse=True)

    # 各種類(最大でK種類目まで)でおいしさが最大のものを保存
    keep = []
    # 取り替えるようのheapq
    exchange = []
    # keepに入っている種類
    types = set()
    for i in range(K):
        d, t = sushi_list[i]
        if t not in types:
            keep.append(d)
            types.add(t)
        else:
            heapq.heappush(exchange, d)

    base_point1 = sum(keep)
    base_point2 = sum(exchange)
    bonus_point = len(types)

    ans = base_point1 + base_point2 + bonus_point ** 2
    
    # K～N番目までをみて、選んでいない種類で最大のものを交換していく
    for i in range(K, N):
        if len(exchange) == 0:
            break

        d, t = sushi_list[i]
        # すでに選んだ種類のものはスキップする
        if t in types:
            continue 
        types.add(t)
        # 選んでいない種類で最大のものを追加する
        base_point1 += d
        # 選んだ種類で最小のものを削除する
        base_point2 -= heapq.heappop(exchange)
        bonus_point += 1
        ans = max(ans, base_point1 + base_point2 + bonus_point ** 2)

    print(ans)


    

main()

Submission status: Accepted

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(min(k, len(leaders)), 0, -1):
    if k - i > len(others):
        break
    score = i ** 2 + cumsum_leaders[i] + cumsum_others[k - i]
    ans = max(ans, score)

print(ans)

Submission status: Accepted

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: Accepted

Solution code:
#00:46
n,k = map(int,input().split())
raw = [[] for _ in range(n)]
for _ in range(n):
  t,d = map(int,input().split())
  t -= 1
  raw[t].append(d)
only = []
other = []
for i in range(n):
  if len(raw[i]) != 0:
    raw[i].sort(reverse = True)
    only.append(raw[i][0])
    other += raw[i][1:]
only.sort(reverse = True)
only += [-10 ** 18 for _ in range(k)]
other.sort(reverse = True)
now = sum(only[:k])
can = [now + k * k]
for j in range(k):
  try:
    now -= only[k-1-j]
    now += other[j]
    can.append(now + (k-1-j) ** 2)
  except:
    break
print(max(can))

Submission status: Accepted

Solution code:
# めちゃよかったのでほぼそのまま　https://atcoder.jp/contests/abc116/submissions/4060186?lang=ja
import heapq
import sys
input = sys.stdin.readline

def main():
	[N,K]=[int(x) for x in input().split()]
	td=[[int(x) for x in input().split()] for _ in range(N)]
	td.sort(key=lambda x:x[1],reverse=True)
	
	# 貪欲にとる.
	keep = []  # 各種類のsushiでおいしさ最大のものを保存
	exchange = []  # 取り替える用 (種類がかぶっているものが入る). priority queue
	types = set() # keepに入っているsushiの種類
	for i in range(K):
	    [t, d] = td[i]
	    if t not in types:
	        keep.append(d)
	        types.add(t)
	    else:
	        heapq.heappush(exchange, d)
	 
	basic_point_1 = sum(keep)
	basic_point_2 = sum(exchange)
	types_bonus = len(types)
	ans = basic_point_1 + basic_point_2 + types_bonus**2
	 
	# 種類が増えるようにおいしさ最大のものから交換していく.
	for i in range(K, N):
	    if len(exchange) == 0:  # 取り替えると種類が減るので終了.
	        break
	    [t, d] = td[i]
	    if t in types:
	        continue
	    types.add(t)
	    basic_point_1 += d
	    basic_point_2 -= heapq.heappop(exchange) # おいしさ最小のものと交換.
	    types_bonus += 1
	    ans = max(ans, basic_point_1 + basic_point_2 + types_bonus**2)
	print(ans)
        
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

from collections import deque

N,K = II()
t,d = Line(N)

x = []
for i in range(N):
    x.append([t[i],d[i]])

x.sort(key=lambda x: -x[1])

used = []
for i in range(K):
    used.append(x[i])

a = defaultdict(list)
for u in used:
    a[u[0]].append(u[1])

num = len(a.keys())

rem = []
for k in a.keys():
    if len(a[k])>=2:
        a[k].sort(reverse=True)
        for i in range(1,len(a[k])):
            rem.append(a[k][i])
rem.sort()
rem = deque(rem)

b = defaultdict(list)
for i in range(N):
    if a[t[i]]==[]:
        b[t[i]].append(d[i])

app = []
for k in b.keys():
    app.append(max(b[k]))
app.sort(reverse=True)
app = deque(app)

val = sum([used[i][1] for i in range(len(used))]) + num**2
temp = val
while (rem and app):
    re,ap = rem.popleft(), app.popleft()
    temp = temp-re+ap-num**2+(num+1)**2
    if val < temp:
        val = temp
    num += 1

print(val)

Submission status: Accepted

Solution code:
from heapq import heappop, heappush
N, K = map(int, input().split())
KMAX = 10 ** 5 + 1
TD = []
for _ in range(N):
    t, d = map(int, input().split())
    TD.append((d, t))

TD.sort(reverse=True)

pioneer = []
successor = []
appear = [False] * KMAX
cnt = 0
nsp = 0  # num of species
base = 0
best = []

for td in TD:
    d, t = td
    if cnt < K:
        heappush(successor if appear[t] else pioneer, (d, t))
        nsp += 0 if appear[t] else 1
        appear[t] = True
        base += d
        cnt += 1
        if cnt == K:
            heappush(best, -(base + nsp ** 2))
        continue
    if not successor:
        break
    if appear[t]:
        continue
    cd, ct = heappop(successor)
    appear[t] = True
    heappush(pioneer, (d, t))
    base += (d-cd)
    nsp += 1
    heappush(best, -(base + nsp ** 2))

print(-heappop(best))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
td = [list(map(int, input().split()))
      for _ in range(N)]
td.sort(key=lambda x: -x[1])
q = []
v = set()
sd = 0
for t, d in td[:K]:
    sd += d
    if t in v:
        q.append(d)
    v.add(t)
ans = len(v) ** 2 + sd
for t, d in td[K:]:
    if 0 >= len(q):
        break
    if t in v:
        continue
    v.add(t)
    md = q.pop()
    sd = sd - md + d
    tans = len(v) ** 2 + sd
    ans = max(ans, tans)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
td = [list(map(int, input().split()))
      for _ in range(N)]
td.sort(key=lambda x: -x[1])
q = []
v = set()
cnt = 0
for t, d in td[:K]:
    cnt += d
    if t in v:
        q.append(d)
    else:
        v.add(t)
cnt += len(v) ** 2
ans = cnt
for t, d in td[K:]:
    if t not in v and len(q) != 0:
        x = q.pop()
        cnt += d + 2 * len(v) + 1 - x
        v.add(t)
        ans = max(ans, cnt)
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
td = sorted([list(map(int, input().split()))
             for _ in range(N)], key=lambda x: x[1], reverse=True)
q = []
v = set()
cnt = 0
for t, d in td[:K]:
    cnt += d
    if t in v:
        q.append(d)
    else:
        v.add(t)
cnt += len(v) ** 2
ans = cnt
for t, d in td[K:]:
    if t not in v and len(q) != 0:
        x = q.pop()
        cnt += d + 2 * len(v) + 1 - x
        v.add(t)
        ans = max(ans, cnt)
print(ans)

Submission status: Accepted

Solution code:
from heapq import heappop, heappush

N, K = map(int, input().split())
td = sorted([list(map(int, input().split()))
             for _ in range(N)], key=lambda x: x[1], reverse=True)
q = []
v = set()
cnt = 0
for t, d in td[:K]:
    cnt += d
    if t in v:
        heappush(q, d)
    else:
        v.add(t)
cnt += len(v) ** 2
ans = cnt
for t, d in td[K:]:
    if t not in v and len(q) != 0:
        x = heappop(q)
        cnt += d + 2 * len(v) + 1 - x
        v.add(t)
        ans = max(ans, cnt)
print(ans)

Submission status: Accepted

Solution code:
from heapq import heappop, heappush
n, k = map(int, input().split())
lst = [list(map(int, input().split())) for i in range(n)]
lst = sorted(lst, reverse=True, key=lambda x:x[1])
q = []
v = set()
cnt = 0
for t, d in lst[:k]:
    cnt += d
    if t in v:
        heappush(q, d)
    else:
        v.add(t)
cnt += len(v)**2
ans = cnt
for t, d in lst[k:]:
    if t not in v and len(q)!=0:
        x = heappop(q)
        cnt += d + 2*len(v) + 1 - x
        v.add(t)
        ans = max(ans, cnt)
print(ans)

Submission status: Accepted

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

N, K = map(int,input().split())
td = [list(map(int, input().split())) for _ in range(N)]
td.sort(key=lambda x: (x[0],x[1]),reverse=True)

x= []
y= []
y.append(td[0][1])
for i in range(1,N):
    if td[i][0] != td[i-1][0]:
        y.append(td[i][1])
    else:
        x.append(td[i][1])
x.sort(reverse=True)
y.sort(reverse=True)
ans = 0
sum_y = 0
sum_x = []
tmp = 0
sum_x.append(0)
for i in range(len(x)):
    tmp += x[i]
    sum_x.append(tmp)

for i in range(1,min(K,len(y))+1):
    sum_y += y[i-1]
    if len(sum_x) < K-i+1: continue
    ans = max(ans, sum_y + sum_x[K-i] + i*i)
    
print(ans)

Submission status: Accepted

Solution code:
n, m = [int(i) for i in input().split()]
td = [[int(i) for i in input().split()] for n in range(n)]
td.sort(key=lambda x:-x[1])
memo = set()
a = []
for t, d in td:
  if t in memo:
    a.append((d, 0))
  else:
    a.append((d, 1))
  memo.add(t)
a = [(-x, x, d) for x, d in a]
import heapq
heapq.heapify(a)
val = 0
kind = 0
b = []
for _ in range(m):
  ele = heapq.heappop(a)
  val += ele[1]
  kind += ele[2]
  if ele[2] == 0:
    b.append(ele[1])
ans = val + kind ** 2
while (len(a) > 0 and len(b)>0):
  val -= b.pop()
  flag = False
  while(len(a) > 0):
    elem = heapq.heappop(a)
    if elem[2] == 1:
      flag = True
      break
  if not flag:
    break
  val += elem[1]
  kind += 1
  tmpans = val + kind ** 2
  if tmpans > ans:
    ans = tmpans
print(ans)

Submission status: Accepted

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

ans = 0
huku = []
su = set([])

for i, j in TD[:k]:
  ans += j
  if i in su:
    huku.append([i,j])
  su.add(i)
ans += len(su)**2
huku.sort(key = lambda x:x[1], reverse = True)

ansl = []
ansl.append(ans)
for i,j in TD[k:]:
  if i in su:
    continue
  elif huku == []:
    break
  else:
    temp = ansl[-1] + j - huku.pop()[1] + (len(su)+1)**2 -len(su)**2
    su.add(i)
    ansl.append(temp)

print(max(ansl))

Submission status: Accepted

Solution code:
from operator import itemgetter


n, k = map(int,input().split())
info = [list(map(int, input().split())) for i in range(n)]

info = sorted(info, key = itemgetter(1), reverse = True)

selected = info[0:k]
selected_only = []
selected_chohuku = []
unselected_only = []
memo = {}
for t, d in selected:
    if t not in memo:
        memo[t] = 1
        selected_only.append(d)
    else:
        selected_chohuku.append(d)

cnt_type = len(memo)
for t, d in info[k:]:
    if t not in memo:
        memo[t] = 1
        unselected_only.append(d)


sum_select = sum(selected_chohuku) + sum(selected_only) 
ans = cnt_type*cnt_type + sum_select

unselected_only = unselected_only[::-1]
for i in range(min(len(selected_chohuku), len(unselected_only))):
    cnt_type += 1
    sum_select += unselected_only[-1]
    sum_select -= selected_chohuku[-1]
    del unselected_only[-1]
    del selected_chohuku[-1]
    tmp = cnt_type*cnt_type + sum_select
    ans = max(ans, tmp)
print(ans)

Submission status: Accepted

Solution code:
mi = lambda: map(int, input().split())
n, k = mi()
sushis = [list(mi()) for _ in range(n)]
types = set()
sushis.sort(key = lambda x: x[1], reverse = True)
bp = tp = sp = 0
exts = []
for t, d in sushis[:k]:
    bp += d
    if t in types:
        exts += d,
    else:
        types.add(t)
        tp += 1
sp = bp+tp**2
for t, d in sushis[k:]:
    if not exts: break
    if t not in types:
        types.add(t)
        bp += d-exts.pop()
        tp += 1
        sp = max(sp, bp+tp**2)
print(sp)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect_left
from heapq import heappush, heappop

def input(): return sys.stdin.readline().strip()
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()
td = [LIST() for _ in range(N)]
td.sort(key=lambda x:-x[1])

q = []
v = set()
s = 0
for t, d in td[:K]:
	s += d
	if t in v:
		heappush(q, d)
	else:  # その種類で最大(最初)のものは以後取り出さないのでヒープに追加しない
		v.add(t)
s += len(v) ** 2  # +種類ボーナス
ans = s

for t, d in td[K:]:  # 残りについて取り替えるか取り替えないか決める
	if t not in v and len(q) != 0:
		z = heappop(q)
		s += d + 2*len(v)+1-z  # 種類ボーナスと満足ボーナスの差分
		v.add(t)
		ans = max(ans, s)
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
a=sorted([list(map(int,input().split()))for i in range(n)],key=lambda x:-x[1])
t=[0]*(n+1)
p,q=0,0
for i in a[:k]:
    p+=i[1]
    if t[i[0]]==0:
        q+=1
    t[i[0]]+=1
s=0
d=p+q*q
c=a[:k][::-1]
for i in a[k:]:
    if t[i[0]]==0:
        while s!=k:
            if t[c[s][0]]==1:
                s+=1
            else:
                break
        if s==k:
            break
        else:
            t[i[0]]+=1
            p-=c[s][1]-i[1]
            q+=1
            d=max(d,p+q*q)
            s+=1
print(d)

Submission status: Accepted

Solution code:
import heapq

N,K = map(int,input().split())

ans = 0

dt = []
maxt = 0

for i in range(N):

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

    dt.append([d,t])

    maxt = max(maxt,t)

dt.sort()
dt.reverse()

nsum = 0
nx = 0
uflag = [0] * (maxt+1)
up2mins = []
amari = []

for i in range(N):

    nt = dt[i][1]
    nd = dt[i][0]

    if i < K:

        nsum += nd

        if uflag[nt] == 0:
            uflag[nt] += 1
            nx += 1

        else:
            heapq.heappush(up2mins,nd)

    else:

        if uflag[nt] == 0:
            heapq.heappush(amari,-1 * nd)
            uflag[nt] += 1

ans = nsum + nx ** 2

#print (up2mins,amari,nsum,nx)

for i in range(N-K+1):

    if len(amari) == 0 or len(up2mins) == 0:
        break

    mnd = heapq.heappop(up2mins)

    pnd = -1 * heapq.heappop(amari)

    nx += 1

    nsum = nsum - mnd + pnd

    ans = max(ans , nsum + nx ** 2)


print (ans)

Submission status: Accepted

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

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)

from collections import Counter
sel=Counter()
ans=0
sta=[]

for t,d in sushi[:k]:
    ans+=d
    sel[t]+=1
    sta.append([t,d])

ans+=len(sel)**2
tmp=ans
for t,d in sushi[k:]:
    if t in sel:continue
    while sta:
        tt,dd=sta.pop()
        if sel[tt]>1:
            tmp+=d-dd+2*len(sel)+1
            ans=max(ans,tmp)
            sel[tt]-=1
            sel[t]+=1
            break
print(ans)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
dts = []
for _ in range(N):
    t, d = map(int, input().split())
    dts.append((d, t-1))

dts.sort(reverse=True)

tops = []
rests = []
isFounds = [False] * N
for d, t in dts:
    if isFounds[t]:
        rests.append(d)
    else:
        tops.append(d)
        isFounds[t] = True

tops.sort(reverse=True)
rests.sort(reverse=True)

xFr = max(1, K-len(rests))
xTo = min(K, len(tops))
iTop = xFr
iRest = K-xFr
sumD = sum(tops[:iTop]) + sum(rests[:iRest])
ans = sumD + xFr**2
for x in range(xFr+1, xTo+1):
    iRest -= 1
    sumD += tops[iTop] - rests[iRest]
    score = sumD + x**2
    ans = max(ans, score)
    iTop += 1

print(ans)

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop

N, K = map(int, input().split())
dts = []
for _ in range(N):
    t, d = map(int, input().split())
    dts.append((d, t-1))

dts.sort(reverse=True)

PQRem = []
isFounds = [False] * N
sumD = 0
for d, t in dts[:K]:
    sumD += d
    if isFounds[t]:
        heappush(PQRem, d)
    isFounds[t] = True
numKind = isFounds.count(True)

PQAdd = []
for d, t in dts[K:]:
    if not isFounds[t]:
        heappush(PQAdd, -d)
    isFounds[t] = True

ans = sumD + numKind**2
for x in range(numKind+1, K+1):
    if not PQRem or not PQAdd:
        break
    dRem = heappop(PQRem)
    dAdd = -heappop(PQAdd)
    sumD += -dRem + dAdd
    score = sumD + x**2
    ans = max(ans, score)

print(ans)

Submission status: Accepted

Solution code:
import heapq

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

for _ in range(N):
    t, d = map(int, input().split())
    sushi.append((t, d))
sushi = sorted(sushi, key=lambda x: -x[1])

d_sushi = []  # 捨てる候補の寿司
heapq.heapify(d_sushi)  # リストaのheap化

fp = 0
tp = set()

for i in range(K):
    fp += sushi[i][1]
    if sushi[i][0] in tp:
        heapq.heappush(d_sushi, sushi[i][1])
    else:
        tp.add(sushi[i][0])
ans = fp+len(tp)**2

if N == K:
    print(ans)
    exit()

j = K
while d_sushi and len(tp) <= N:
    while sushi[j][0] in tp:
        j += 1
        if j == N:
            print(ans)
            exit()
    fp = fp-heapq.heappop(d_sushi)+sushi[j][1]
    tp.add(sushi[j][0])
    ans = max(ans, fp+len(tp)**2)

print(ans)