input
stringlengths
20
127k
target
stringlengths
20
119k
problem_id
stringlengths
6
6
import collections N,K = list(map(int,input().split())) A = list(map(int,input().split())) sum = 0 tmp = len(list(set(A))) li = collections.Counter(A) for i in range(K,tmp,1): sum += li.most_common()[i][1] print(sum)
import collections N,K = list(map(int,input().split())) A = list(map(int,input().split())) ans = 0 tmp = len(list(set(A))) li = collections.Counter(A) value,counts = list(zip(*li.most_common())) for i in range(K,tmp,1): ans += counts[i] print(ans)
p03495
from collections import Counter n, k = list(map(int, input().split())) a = Counter((i for i in input().split())) sort_count = sorted(list(a.items()), key=lambda x: x[1]) total = 0 while len(sort_count) > k: _, n = sort_count.pop(0) total += n print(total)
from collections import Counter n, k = list(map(int, input().split())) a = Counter((i for i in input().split())) sort_count = sorted(a.values()) total = 0 l = len(sort_count) if len(sort_count) <= k: print((0)) else: print((sum(sort_count[:l-k])))
p03495
from collections import defaultdict n, k = [int(x) for x in input().split()] a_list = [int(x) for x in input().split()] d = defaultdict(int) for a in a_list: d[a] += 1 print((sum(sorted(d.values())[:-k])))
from collections import defaultdict n, k = [int(x) for x in input().split()] a_list = [int(x) for x in input().split()] d = defaultdict(int) for a in a_list: d[a] += 1 print((sum(sorted(list(d.values()), reverse=True)[k:])))
p03495
n, k = list(map(int, input().split())) nums = list(map(int, input().split())) def judge(n, k, nums): original = nums types = set(nums) diff = len(types) - k count = [] ans = 0 if len(types) <= k: return 0 for i in types: count.append(original.count(i)) count.sort() for i in range(diff): ans += count[i] return ans print((judge(n, k, nums)))
n, k = list(map(int, input().split())) nums = list(map(int, input().split())) def judge(n, k, nums): original = nums types = set(nums) diff = len(types) - k count = [] temp_count = 0 temp_char = nums[0] ans = 0 nums.sort() if len(types) <= k: return 0 for i in range(n): if nums[i] == temp_char: temp_count += 1 else: temp_char = nums[i] if not temp_count == 0: count.append(temp_count) temp_count = 1 if i == n-1: if not temp_count == 0: count.append(temp_count) count.sort() return sum(count[:diff]) print((judge(n, k, nums)))
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) a = sorted(a) p = list(set(a)) if len(p) <= k: print('0') exit() j = 0 ans = [0 for _ in range(len(p))] for i in range(len(p)): ans[i] += a.count(p[i]) ans = sorted(ans) print((sum(ans[:len(p) - k])))
n, k = list(map(int, input().split())) a = list(map(int, input().split())) a = sorted(a) p = list(set(a)) if len(p) <= k: print('0') exit() j = 0 ans = [0 for _ in range(len(p))] ans[0] = 1 for i in range(1, n): if a[i] == a[i - 1]: ans[j] += 1 else: j += 1 ans[j] += 1 ans = sorted(ans) print((sum(ans[:len(p) - k])))
p03495
N, K = list(map(int, input().split())) A = list(map(int, input().split())) import collections c = collections.Counter(A) values, counts = list(zip(*c.most_common()[::-1])) counts = list(counts) cnt = 0 inf = 10 ** 18 for _ in range(inf): if len(counts) <= K: print(cnt) break cnt += counts[0] counts = counts[1:]
N, K = list(map(int, input().split())) A = list(map(int, input().split())) import collections from itertools import accumulate c = collections.Counter(A) _, counts = list(zip(*c.most_common()[::-1])) counts = list(accumulate(counts)) cnt = 0 inf = 10 ** 18 target = len(counts) - K if target <= 0: print((0)) else: print((counts[target-1]))
p03495
n,k = list(map(int,input().split())) a = list(map(int,input().split())) s = set(a) r = [] for i in s: r.append(a.count(i)) r = sorted(r) dif = len(s) - k print((sum(r[0:max(0,dif)])))
import itertools n,k = list(map(int,input().split())) a = sorted(list(map(int,input().split()))) c = [] g = itertools.groupby(a) for m,v in g: c.append(len(list(v))) c = sorted(c) print((sum(c[:-k])))
p03495
N, K = [int(i) for i in input().split()] B = sorted([int(i) for i in input().split()]) D ={} bag = 0 for i in B: if i in D: D[i] += 1 else: D[i] = 1 LLL = sorted(list(D.values())) AA = len(D) - K if len(D) <= K: print((0)) else: for i in range(AA): bag += LLL[i] print(bag)
N, K = [int(i) for i in input().split()] A = [int(i) for i in input().split()] dic = {} for i in A: if i in dic: dic[i] += 1 else: dic[i] = 1 dic_sort = sorted(list(dic.items()), key=lambda x:x[1], reverse=True) ans = [] for i in range(K, len(dic_sort)): ans.append(dic_sort[i][1]) print((sum(ans)))
p03495
from collections import Counter from collections import defaultdict N, K = list(map(int, input().split())) A = list(map(int, input().split())) B = Counter(A).most_common() dict = [] for l in B: dict.append([l[0], l[1]]) dict.sort(key=lambda x:x[1]) count = 0 l = len(B) if l <= K: print((0)) else: while l != K: count += dict[0][1] del dict[0] dict.sort(key=lambda x:x[1]) l = len(dict) if l == K: break print(count)
from collections import Counter N, K = list(map(int, input().split())) A = list(map(int, input().split())) ca = Counter(A) ca = sorted(list(ca.items()), key=lambda x:x[1], reverse=True) ans = 0 for i in range(min(K, len(ca))): ans += ca[i][1] print((N-ans))
p03495
import sys import collections if sys.platform =='ios': sys.stdin=open('Untitled.txt') N, K = [int(x) for x in input().split()] nums = [int(x) for x in input().split()] count = 0 while len(set(nums)) > K: c = collections.Counter(nums) ma = c.most_common()[0] mi = c.most_common()[-1] nums = [ma[0] if i == mi[0] else i for i in nums] count += mi[1] print(count)
import sys import collections if sys.platform =='ios': sys.stdin=open('Untitled.txt') N, K = [int(x) for x in input().split()] nums = [int(x) for x in input().split()] c = collections.Counter(nums) d = c.most_common()[::-1] print((sum([d[i][1] for i in range(len(d) - K)])))
p03495
N,K=[int(i) for i in input().split()] A=[int(i) for i in input().split()] s=[0 for i in range(200000)] for i in range(200000): t=A.count(i) s[i]+=t s.sort() s.reverse() p=0 for i in range(K): p+=s[i] print((N-p))
s=0 R=[] N,K=[int(i) for i in input().split()] A=[int(i) for i in input().split()] import collections c=collections.Counter(A).most_common() # for i in c.values(): # R.append(i) if len(c)>K: for i in range(K): s+=c[i][1] print((N-s)) else: print("0")
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) dic = {} for num in a: if num not in list(dic.keys()): dic[num] = 0 dic[num] += 1 dic = sorted(list(dic.items()), key=lambda x:x[1]) ans = 0 for i in range(len(dic)- k): ans += dic[i][1] print(ans)
n, k = list(map(int, input().split())) a = list(map(int, input().split())) b = [0] * n for i in range(n): b[a[i] - 1] += 1 b.sort(reverse=True) ans = 0 for i in range(k): ans +=b[i] if n - ans <= 0: print((0)) else: print((n - ans))
p03495
from collections import Counter n,k = list(map(int,input().split())) n_lst = list(map(int,input().split())) cnt_lst = Counter(n_lst).most_common()[k:] ans = 0 for x in cnt_lst: ans += x[1] print(ans)
n,k = list(map(int,input().split())) n_lst = list(map(int,input().split())) cnt_lst = [0 for _ in range(n+1)] for x in n_lst: cnt_lst[x] += 1 cnt_lst.sort(reverse=True) print((sum(cnt_lst[k:])))
p03495
import collections N, K = list(map(int, input().split())) A = list(map(int, input().split())) A = dict(collections.Counter(A)) cnt = 0 for i in range(N): if len(A) > K: min_k = min(A, key=A.get) cnt += A[min_k] A.pop(min_k) else: break print(cnt)
import collections N, K = list(map(int, input().split())) A = list(map(int, input().split())) A = dict(collections.Counter(A)) A = sorted(list(A.items()), key=lambda x: x[1], reverse=True) cnt = 0 for i in range(N): if len(A) > K: cnt += A[-1][1] A.pop() else: break print(cnt)
p03495
import sys from math import sqrt from collections import Counter input = sys.stdin.readline def I(): return int(sys.stdin.readline()) def MI(): return list(map(int, sys.stdin.readline().split())) inf = float("inf") mod = 10 ** 9 + 7 def main(): n, k = MI() a_list = MI() c = Counter(a_list) n_key = len(c) n_rewrite = 0 while n_key > k: n_rewrite += c.pop(c.most_common()[-1][0]) n_key -= 1 print(n_rewrite) pass if __name__ == "__main__": main()
import sys from math import sqrt from collections import Counter input = sys.stdin.readline def I(): return int(sys.stdin.readline()) def MI(): return list(map(int, sys.stdin.readline().split())) inf = float("inf") mod = 10 ** 9 + 7 def main(): n, k = MI() a_list = MI() c = Counter(a_list) sum = 0 if len(c) <= k: print("0") exit() for l in c.most_common()[k:]: sum += l[1] print(sum) pass if __name__ == "__main__": main()
p03495
N,K = list(map(int,input().split())) A = list(map(int,input().split())) D = {} for i in range(N) : if A[i] not in D : D[A[i]] = 1 else : D[A[i]] += 1 L = list(D.values()) L = sorted(L) ans = 0 for i in range(len(L)) : if len(L) > K : ans += L[0] L.pop(0) print(ans)
N,K = list(map(int,input().split())) A = list(map(int,input().split())) D = {} for i in A : if i in D : D[i] += 1 else : D[i] = 1 D = sorted(list(D.items()),key=lambda x:x[1]) counter = 0 answer = 0 for j in range(len(D)) : if len(D) - counter > K : counter += 1 answer += D[j][1] else : print(answer) break
p03495
N, K = [int(nk) for nk in input().split()] A = [int(a) for a in input().split()] A_set = list(set(A)) if len(A_set) <= K: print((0)) else: AA = [A.count(i) for i in A_set] AA.sort() ans = sum(AA[:-K]) print(ans)
N, K = [int(nk) for nk in input().split()] A = [int(a) for a in input().split()] A_set = list(set(A)) if len(A_set) <= K: print((0)) else: # len(A_set) > K: dictionary = {} for n in A_set: dictionary[n] = 0 for m in A: dictionary[m] += 1 dict_val = list(dictionary.values()) dict_val.sort(reverse = True) ans = N - sum(dict_val[:K]) print(ans)
p03495
def 解(): iN,iK = [int(_) for _ in input().split()] aA = [int(_) for _ in input().split()] dA = {} def addD(d,a): if a in d: d[a] += 1 else: d[a] = 1 for a in aA: addD(dA,a) aList = sorted(list(dA.items()),key=lambda x:x[1]) print((sum([x[1] for x in aList[0:len(aList)-iK]]))) 解()
def 解(): iN,iK = [int(_) for _ in input().split()] #aA = [int(_) for _ in input().split()] dA = {} def addD(d,a): if a in d: d[a] += 1 else: d[a] = 1 for a in [int(_) for _ in input().split()]: addD(dA,a) aList = sorted(list(dA.items()),key=lambda x:x[1]) print((sum([x[1] for x in aList[0:len(aList)-iK]]))) 解()
p03495
N,K = list(map(int,input().split())) balls = [] bucket = [0]*(N+1) balls = list(map(int,input().split())) balls.sort() for ball_number in balls: bucket[ball_number] += 1 def judge(number_of_types, types): if number_of_types <= types: return True number_of_types = 0 for i in bucket: if i >= 1: number_of_types += 1 if number_of_types <= K: print("0") quit() else: count = 0 for i in range(1,N+1): for j in bucket: if j == i: count += i number_of_types -= 1 if judge(number_of_types, K): print(count) quit()
N,K=list(map(int,input().split())) A=list(map(int,input().split())) A.sort() bucket=[0*i for i in range(N+1)] count=1 types=1 for i in range(1,N): if A[i]==A[i-1]: if i!=N-1: count+=1 else: count+=1 bucket[count]+=1 break else: types+=1 if i!=N-1: bucket[count]+=1 count=1 else: bucket[count]+=1 bucket[1]+=1 break i=1 number_of_changes=0 while True: if types<=K: print((0)) quit() elif types-bucket[i]<=K: print(((types-K)*i+number_of_changes)) quit() else: types-=bucket[i] number_of_changes+=bucket[i]*i i+=1
p03495
N, K = list(map(int,input().split())) A = list(map(int,input().split())) d = {} for a in A: if(a not in d): d[a] = 1 else: d[a] += 1 print((sum(sorted(d.values())[:-K])))
N, K = list(map(int,input().split())) A = list(map(int,input().split())) d = {} for a in A: if(a in d): d[a] += 1 else: d[a] = 1 print((sum(sorted(d.values())[:-K])))
p03495
n, k = list(map(int,input().split())) a = list(map(int,input().split())) d = [] c = [] for i in range(n): if not a[i] in d: d.append(a[i]) c.append(a.count(a[i])) c.sort(reverse=True) print((n-sum(c[0:k])))
n, k = list(map(int,input().split())) a = list(map(int,input().split())) d = {} for i in a: if i in d: d[i] += 1 else: d[i] = 1 c = sorted(list(d.items()),key = lambda x:x[1], reverse=True) ans = 0 for i in range(min(k,len(c))): ans += c[i][1] print((n-ans))
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) from collections import Counter, OrderedDict c = Counter(a) d = OrderedDict(sorted(list(c.items()), key=lambda x: x[1])) if len(d) <= k: print((0)) else: ans = 0 while len(d) > k: item = list(d.items())[0] ans += item[1] del d[item[0]] print(ans)
n, k = list(map(int, input().split())) a = list(map(int, input().split())) from collections import Counter c = Counter(a) d = c.most_common() if len(d) <= k: print((0)) else: ans = 0 while len(d) > k: item = d.pop() ans += item[1] print(ans)
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) cnt_list = [] cnt_dict = {} for i in a: if i in cnt_dict: cnt_dict[i] += 1 else: cnt_dict[i] = 1 cnt_dict_sorted = sorted(list(cnt_dict.items()), key=lambda x: x[1]) for i in set(a): cnt_list.append(a.count(i)) ans = 0 if len(cnt_dict_sorted) <= k: ans = 0 else: tmp = len(cnt_dict_sorted) - k for j in range(tmp): ans += cnt_dict_sorted[j][1] print(ans)
n, k = list(map(int, input().split())) a = list(map(int, input().split())) cnt_dict = {} for i in a: if i in cnt_dict: cnt_dict[i] += 1 else: cnt_dict[i] = 1 cnt_dict_sorted = sorted(list(cnt_dict.items()), key=lambda x: x[1]) ans = 0 if len(cnt_dict_sorted) <= k: ans = 0 else: tmp = len(cnt_dict_sorted) - k for j in range(tmp): ans += cnt_dict_sorted[j][1] print(ans)
p03495
n,k=list(map(int,input().split())) a=list(map(int,input().split())) if len(list(set(a)))<=k: print((0)) else: l=[0]*n for i in range(n): l[a[i]-1]+=1 l.sort() ans=0 cnt=0 i=0 while cnt<(len(list(set(a)))-k): if l[i]!=0: ans+=l[i] cnt+=1 i+=1 else: i+=1 print(ans)
n,k=list(map(int,input().split())) a=list(map(int,input().split())) if len(list(set(a)))<=k: print((0)) else: d={} for i in range(n): if a[i] in d: d[a[i]]+=1 else: d[a[i]]=1 d=sorted(list(d.items()),key=lambda x:x[1]) m=len(d) cnt=0 for i in range((len(list(set(a))))-k): cnt+=d[i][1] print(cnt)
p03495
from collections import Counter n,k=list(map(int,input().split())) A=list(map(int,input().split())) s=len(set(A)) C=Counter(A) if s>k: for i in range(k): n-=C.most_common()[i][1] print(n) else: print((0))
n,k=list(map(int,input().split())) A=list(map(int,input().split())) d={} for a in A: if a in d: d[a]+=1 else: d[a]=1 D=sorted(list(d.items()), key=lambda x:x[1], reverse=True) if len(set(A))>k: for i in range(k): n-=D[i][1] print(n) else: print((0))
p03495
#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 def main(): N, K = list(map(int, input().split())) A = list(map(int, input().split())) L = [] B = set(A) for i in B: L.append(A.count(i)) L.sort() if len(B) <= K: print('0') else: print((str(sum(L[0:len(B)-K])))) if __name__ == "__main__": main()
#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 def main(): N, K = list(map(int, input().split())) A = list(map(int, input().split())) B = set(A) L = [0 for i in range(N+1)] for i in A: L[i] += 1 L.sort() if len(B) <= K: print('0') else: print((str(sum(L[0:N+1-K])))) if __name__ == "__main__": main()
p03495
from collections import Counter n,k=list(map(int,input().split())) a=Counter(list(map(int,input().split()))) cnt=0 ls=[] if len(a)>k: for i in range(len(a)): ls.append(a.most_common()[i][1]) print((sum(ls[k:])))
n,k=list(map(int,input().split())) a=list(map(int,input().split())) d={} for i in a: d[i]=d.get(i,0)+1 s=sorted(d.values()) print((sum(s[:len(s)-k]))) # x
p03495
from collections import Counter N,K = list(map(int, input().split())) A = Counter(list(map(int, input().split()))) B = list(A.items()) k = len(B) - K if k <= 0: print((0)) else: print((sum([sorted(B,key=lambda x:x[1])[i][1] for i in range(k)])))
from collections import Counter N,K = list(map(int, input().split())) A = Counter(list(map(int, input().split()))) B = list(A.values()) k = len(B) - K if k <= 0: print((0)) else: print((sum(sorted(B)[0:k])))
p03495
from collections import Counter N,K = list(map(int, input().split())) A = Counter(list(map(int, input().split()))) B = list(A.values()) k = len(B) - K if k <= 0: print((0)) else: print((sum(sorted(B)[0:k])))
from collections import Counter N,K = list(map(int, input().split())) A = Counter(input().split()) B = list(A.values()) k = len(B) - K if k <= 0: print((0)) else: print((sum(sorted(B)[0:k])))
p03495
N,K = list(map(int,input().split(" "))) A = list(map(int,input().split(" "))) num = list(set(A)) ans=[] for n in num: ans.append(A.count(n)) print((sum(sorted(ans)[:len(ans)-K:])))
N,K = list(map(int,input().split(" "))) d={} for i in input().split(" "): if i in d: d[i]+=1 else: d[i]=1 print((sum(sorted(d.values())[:len(list(d.keys()))-K:])))
p03495
nk = list(map(int,input().split())) a = list(map(int,input().split())) sa = list(set(a)) if len(sa) > nk[1]: c = [] for i in range(len(sa)): c.append(a.count(sa[i])) sortc = sorted(c, reverse = True) m = 0 for i in range(nk[1]): m += sortc[i] ans = nk[0] - m else: ans = 0 print(ans)
nk = list(map(int,input().split())) a = list(map(int,input().split())) cli = [] for i in range(nk[0]+1): cli.append(0) for i in range(nk[0]): cli[a[i]] += 1 c = sorted(cli, reverse = True) m = 0 for i in range(nk[1]): m += c[i] ans = nk[0] - m if ans < 0: ans = 0 print(ans)
p03495
n, k = list(map(int, input().split())) a = list(map(int, input().split())) count = dict() for i in a: count[i] = count.get(i, 0) + 1 ans = 0 while len(count) > k: key, value = min(list(count.items()), key=lambda x : x[1]) del count[key] ans += value print(ans)
n, k = list(map(int, input().split())) a = list(map(int, input().split())) count = {} for i in a: count[i] = count.get(i, 0) + 1 print((sum(sorted(count.values())[:-k])))
p03495
N, K = list(map(int, input().split())) A = list(map(int, input().split())) A_dict = {str(i):0 for i in set(A)} for a in A: A_dict[str(a)] += 1 del A def get_A_key_from_value(dic, value): for i, j in list(dic.items()): if j == value: break return i ans = 0 while True: if len(A_dict) <= K: break ans += min(A_dict.values()) del A_dict[get_A_key_from_value(A_dict,min(A_dict.values()))] print(ans)
#読み込み N, K = list(map(int, input().split())) A = list(map(int, input().split())) #処理回数 reduce_type = len(set(A)) - K #削除する数の選定 A_dict = {str(i):0 for i in set(A)} for a in A: A_dict[str(a)] += 1 del A list_del_num = sorted(list(A_dict.values()))[:reduce_type] #計算 ans = sum(list_del_num) print(ans)
p03495
N,K=list(map(int,input().split())) a=list(map(int,input().split())) d=[0]*N ans=0 for i in range(N): d[a[i]-1]+=1 d.sort(reverse=True) while len(d)>K: if i!=0: ans += d.pop(K) else: break print(ans)
N,K=list(map(int,input().split())) a=list(map(int,input().split())) d=[0]*N ans=0 for i in range(N): d[a[i]-1]+=1 d.sort(reverse=True) if len(d)>K: ans =sum(d[K:]) print(ans)
p03495
def resolve(): # 整数 1 つ # n = int(input()) # 整数複数個 n, k = list(map(int, input().split())) # 整数 N 個 (改行区切り) # N = [int(input()) for i in range(N)] # 整数 N 個 (スペース区切り) A = list(map(int, input().split())) # 整数 (縦 H 横 W の行列) # A = [list(map(int, input().split())) for i in range(H)] Unique = list(set(A)) Dic = {x:A.count(x) for x in set(A)} if len(set(A)) <= k: print((0)) else: Dicsort = sorted(list(Dic.items()), key=lambda x: x[1]) cnt = 0 for i in range(len(set(A)) - k): cnt += Dicsort[i][1] print(cnt) resolve()
N,K = list(map(int,input().split())) A = list(map(int,input().split())) Ad = {x:0 for x in set(A)} if len(set(A)) <= K: print((0)) else: count = 0 for a in A: Ad[a] += 1 Ad = sorted(list(Ad.items()), key=lambda x:x[1]) for i in range(len(set(A))-K): count += Ad[i][1] print(count)
p03495
def resolve(): # 整数 1 つ # n = int(input()) # 整数複数個 n, k = list(map(int, input().split())) # 整数 N 個 (改行区切り) # N = [int(input()) for i in range(N)] # 整数 N 個 (スペース区切り) A = list(map(int, input().split())) # 整数 (縦 H 横 W の行列) # A = [list(map(int, input().split())) for i in range(H)] Unique = list(set(A)) Dic = {x:0 for x in set(A)} if len(set(A)) <= k: print((0)) else: for x in A: Dic[x] += 1 Dicsort = sorted(list(Dic.items()), key=lambda x: x[1]) cnt = 0 for i in range(len(set(A)) - k): cnt += Dicsort[i][1] print(cnt) resolve()
def resolve(): # 整数 1 つ # n = int(input()) # 整数複数個 n, k = list(map(int, input().split())) # 整数 N 個 (改行区切り) # N = [int(input()) for i in range(N)] # 整数 N 個 (スペース区切り) A = list(map(int, input().split())) # 整数 (縦 H 横 W の行列) # A = [list(map(int, input().split())) for i in range(H)] Dic = {x:0 for x in set(A)} if len(Dic) <= k: print((0)) else: for i in A: Dic[i] += 1 Dicsort = sorted(list(Dic.items()), key=lambda x: x[1]) cnt = 0 for j in range(len(Dic) - k): cnt += Dicsort[j][1] print(cnt) resolve()
p03495
N,K = list(map(int,input().split())) A =list(map(int,input().split())) num = [0]*2000001 for i in range(N): num[A[i]] +=1 V = 2000001 - num.count(0) if V <=K: print((0)) else: num.sort() num.reverse() print((sum(num[K:])))
N,K = list(map(int,input().split())) A =list(map(int,input().split())) num = [0]*(N+1) for i in range(N): num[A[i]] +=1 V = N+1 - num.count(0) if V <=K: print((0)) else: num.sort() num.reverse() print((sum(num[K:])))
p03495
import collections n,k = (int(i) for i in input().split()) a = list(int(i) for i in input().split()) c = collections.Counter(a) ct = 0 for i in range(k): try: ct += c.most_common()[i][1] except: break ans = n-ct if ans <0: ans = 0 print(ans)
import collections n,k = (int(i) for i in input().split()) a = list(int(i) for i in input().split()) c = collections.Counter(a) values,counts = list(zip(*c.most_common())) if len(counts) >= k: ans = sum(counts[k:]) else: ans = 0 print(ans)
p03495
from collections import Counter, deque, defaultdict n, k = list(map(int, input().split())) A = list(map(int, input().split())) t = defaultdict(int) for x in A: t[x]+=1 B = [] for x in list(t.values()): B.append(x) B.sort() if(len(B)<=k): print((0)) exit() ans = 0 for i in range(0, len(B)): ans+=B[i] if len(B)-(i+1) <= k: break print(ans)
from collections import Counter, deque, defaultdict n, k = list(map(int, input().split())) A = list(map(int, input().split())) t = defaultdict(int) for x in A: t[x]+=1 B = list(t.values()) B.sort() if(len(B)<=k): print((0)) exit() ans = sum(B[:len(B)-k]) print(ans)
p03495
from collections import Counter as C _, k = list(map(int, input().split())) a = [int(i) for i in input().split()] ans = 0 c = sorted(C(a).values()) while k < len(c): ans += c.pop(0) else: print(ans)
from collections import Counter, deque _, k = list(map(int, input().split())) a = [int(i) for i in input().split()] ans = 0 d = deque(sorted(Counter(a).values())) while k < len(d): ans += d.popleft() else: print(ans)
p03495
from collections import Counter, deque _, k = list(map(int, input().split())) a = [int(i) for i in input().split()] ans = 0 d = deque(sorted(Counter(a).values())) while k < len(d): ans += d.popleft() else: print(ans)
from collections import Counter as C _, k = list(map(int, input().split())) a = [int(i) for i in input().split()] c = list(C(a).values()) d = len(c) - k if 0 < d: print((sum(sorted(c)[:d]))) else: print((0))
p03495
from collections import Counter n, k = list(map(int, input().split())) A = Counter([int(i) for i in input().split()]).most_common() count = 0 if len(A) > k: for i in range(len(A) - k): count += A[k + i][1] print(count)
from collections import Counter N, K = list(map(int, input().split())) A = Counter([int(i) for i in input().split()]).most_common() cnt = 0 for a in A[K:]: cnt += a[1] print(cnt)
p03495
N, K = list(map(int, input().split())) A = list(map(int, input().split())) set_A = set(A) len_types = len(set_A) memo = [0] * N ans = 0 for num in set_A: count_num = A.count(num) memo[num-1] = count_num memo.sort() for i in memo[:N-K]: ans += i # while len_types > K: # ans += heapq.heappop(memo) # len_types -= 1 print(ans)
N, K = list(map(int, input().split())) A = list(map(int, input().split())) memo = [0] * N ans = 0 for a in A: memo[a-1] += 1 memo.sort() for i in memo[:N-K]: ans += i print(ans)
p03495
from collections import Counter N, K = list(map(int, input().split())) cnt = Counter(list(map(int, input().split()))) res = 0 l = len(cnt) for i in range(l, K, -1): res += cnt.most_common(i)[-1][1] print(res)
from collections import Counter N, K = list(map(int, input().split())) cnt = Counter(list(map(int, input().split()))) res = 0 l = len(cnt) mc = cnt.most_common() for i in range(l - 1, K - 1, -1): res += mc[i][1] print(res)
p03495
from collections import Counter n, k = list(map(int, input().split())) a = list(map(int, input().split())) d = Counter(a) d = d.most_common() ans = 0 for i in range(len(d) - k): ans += d[-i - 1][1] print(ans)
from collections import Counter n, k = list(map(int, input().split())) a = input().split() d = sorted(Counter(a).values()) ans = 0 for i in range(len(d) - k): ans += d[i] print(ans)
p03495
def main(): n, k = list(map(int, input().split())) A = list(map(int, input().split())) res = 0 balls = {} for ball in A: if ball in balls: balls[ball] += 1 else: balls[ball] = 1 delList = [] bucket = [0 for _ in range(n+1)] for a in A: bucket[a] += 1 for i in range(len(bucket)): if bucket[i] == 0: bucket[i] = 10**9 for _ in range(len(set(A))): minBucket = min(bucket) minBucketIdx = bucket.index(minBucket) delList.append(minBucketIdx) bucket[minBucketIdx] = 10**9 while len(delList) > k: res += balls[delList[0]] delList.pop(0) print(res) if __name__ == '__main__': main()
def main(): n, k = list(map(int, input().split())) A = list(map(int, input().split())) res = 0 balls = {} bucket = [[] for _ in range(n+1)] for ball in A: if ball in balls: balls[ball] += 1 else: balls[ball] = 1 for key, value in list(balls.items()): bucket[value].append(key) for i in range(len(bucket)): for j in range(len(bucket[i])): if bucket[i] != [] and len(balls) > k: res += i balls.pop(bucket[i][j]) print(res) if __name__ == '__main__': main()
p03495
import queue que = queue.PriorityQueue() dic = { ord('r')+ord('g'): 'b', ord('g')+ord('b'): 'r', ord('b')+ord('r'): 'g', } while True: s = input() if s=='0': break while not que.empty(): que.get() cost = {} cost[s] = 0 que.put((0, s)) ans = -1 while not que.empty(): nn, ss = que.get() if all(e == ss[0] for e in ss): ans = nn break if cost[ss] < nn: continue for i in range(len(ss)-1): c0, c1 = ss[i], ss[i+1] if c0 != c1: code = dic[ord(c0)+ord(c1)] sa = ss[:i] + code*2 + ss[i+2:] if sa not in cost or nn+1 < cost[sa]: cost[sa] = nn+1 que.put((nn+1, sa)) print("NA" if ans<0 else ans)
import queue dic = { 'rg':'b', 'gr':'b', 'gb':'r', 'bg':'r', 'br':'g', 'rb':'g', } while True: s = input() if s=='0': break que = queue.PriorityQueue() l = len(s) cost = {} cost[s] = 0 que.put((0, s)) ans = -1 while not que.empty(): nn, ss = que.get() if all(e == ss[0] for e in ss): ans = nn break if cost[ss] < nn: continue for i in range(l-1): cc = ss[i:i+2] if cc[0]!=cc[1]: code = dic[cc] sa = ss[:i] + code*2 + ss[i+2:] if sa not in cost or nn+1 < cost[sa]: cost[sa] = nn+1 que.put((nn+1, sa)) print("NA" if ans<0 else ans)
p00179
import queue dic = { 'rg':'b', 'gr':'b', 'gb':'r', 'bg':'r', 'br':'g', 'rb':'g', } while True: s = input() if s=='0': break que = queue.PriorityQueue() l = len(s) cost = {} cost[s] = 0 que.put((0, s)) ans = -1 while not que.empty(): nn, ss = que.get() if all(e == ss[0] for e in ss): ans = nn break if cost[ss] < nn: continue for i in range(l-1): cc = ss[i:i+2] if cc[0]!=cc[1]: code = dic[cc] sa = ss[:i] + code*2 + ss[i+2:] if sa not in cost or nn+1 < cost[sa]: cost[sa] = nn+1 que.put((nn+1, sa)) print("NA" if ans<0 else ans)
import queue dic = { 'rg':'bb', 'gr':'bb', 'gb':'rr', 'bg':'rr', 'br':'gg', 'rb':'gg', } while True: s = input() if s=='0': break que = queue.PriorityQueue() l = len(s) cost = {s: 0} que.put((0, s)) aa = ['r'*l, 'g'*l, 'b'*l] ans = -1 while not que.empty(): nn, ss = que.get() if ss in aa: ans = nn break if cost[ss] < nn: continue for i in range(l-1): cc = ss[i:i+2] if cc[0]!=cc[1]: sa = ss[:i] + dic[cc] + ss[i+2:] if sa not in cost or nn+1 < cost[sa]: cost[sa] = nn+1 que.put((nn+1, sa)) print("NA" if ans<0 else ans)
p00179
rgb = set(["r","g","b"]) while 1: worm = input() if worm == "0": break n = len(worm) que = [worm] ref = set(worm) L = 1 cnt = flag = 0 while 1: for r in range(L): Worm = que.pop(0) if Worm in ref: continue else: ref.add(Worm) if len(set(Worm)) == 1: flag = 1 break for i in range(n-1): if Worm[i] != Worm[i+1]: worm = Worm[:] nextclr = list(rgb-set(worm[i:i+2]))[0] worm = worm[:i] + 2*nextclr + worm[i+2:] if worm not in que: que.append(worm) L = len(que) if flag or L == 0: break cnt += 1 if cnt > 15: break print(cnt if flag else "NA")
rgb = set(["r","g","b"]) while 1: worm = input() if worm == "0": break n = len(worm) L = 1 cnt = flag = 0 queset = set([worm]) while 1: que = list(queset) queset = set() for r in range(L): Worm = que.pop(0) if len(set(Worm)) == 1: flag = 1 break for i in range(n-1): if Worm[i] != Worm[i+1]: nextclr = list(rgb-set(Worm[i:i+2]))[0] worm = Worm[:i] + 2*nextclr + Worm[i+2:] queset.add(worm) L = len(queset) if flag: break cnt += 1 if cnt > 15: break print(cnt if flag else "NA")
p00179
rgb = set(["r","g","b"]) while 1: worm = input() if worm == "0": break n = len(worm) L = 1 cnt = flag = 0 queset = set([worm]) while 1: que = list(queset) queset = set() for r in range(L): Worm = que.pop(0) if len(set(Worm)) == 1: flag = 1 break for i in range(n-1): if Worm[i] != Worm[i+1]: nextclr = list(rgb-set(Worm[i:i+2]))[0] worm = Worm[:i] + 2*nextclr + Worm[i+2:] queset.add(worm) L = len(queset) if flag: break cnt += 1 if cnt > 15: break print(cnt if flag else "NA")
rgb = set(["r","g","b"]) while 1: worm = input() if worm == "0": break n = len(worm) L = 1 cnt = flag = 0 queset = set([worm]) ref = set() while 1: que = list(queset) queset = set() for Worm in que: if len(set(Worm)) == 1: flag = 1 break for i in range(n-1): if Worm[i] != Worm[i+1]: nextclr = list(rgb-set(Worm[i:i+2]))[0] worm = Worm[:i] + 2*nextclr + Worm[i+2:] queset.add(worm) queset = queset - ref ref = ref|queset L = len(queset) if flag: break cnt += 1 if cnt > 15: break print(cnt if flag else "NA")
p00179
rgb = set(["r","g","b"]) while 1: worm = input() if worm == "0": break n = len(worm) L = 1 cnt = flag = 0 queset = set([worm]) ref = set() while 1: que = list(queset) queset = set() for Worm in que: if len(set(Worm)) == 1: flag = 1 break for i in range(n-1): if Worm[i] != Worm[i+1]: nextclr = list(rgb-set(Worm[i:i+2]))[0] worm = Worm[:i] + 2*nextclr + Worm[i+2:] queset.add(worm) queset = queset - ref ref = ref|queset L = len(queset) if flag: break cnt += 1 if cnt > 15: break print(cnt if flag else "NA")
dic = {"r":1,"g":2,"b":3} rgb = ["r","g","b"] while 1: worm = input() if worm == "0": break n = len(worm) ref = ["r"*n,"g"*n,"b"*n] cnt = flag = 0 queset = set([worm]) done = set() while 1: que = list(queset) queset = set() for Worm in que: if Worm in ref: flag = 1 break for i in range(n-1): if Worm[i] != Worm[i+1]: nextclr = rgb[5-dic[Worm[i]]-dic[Worm[i+1]]] queset.add(Worm[:i] + 2*nextclr + Worm[i+2:]) if flag or cnt > 14: break cnt += 1 queset -= done done |= queset print(cnt if flag else "NA")
p00179
from statistics import mean inputCount = int(eval(input())) prices = [int(eval(input())) for lp in range(inputCount)] average = mean(prices) print((int(average)))
inputCount = int(eval(input())) prices = [int(eval(input())) for lp in range(inputCount)] average = sum(prices) // inputCount print(average)
p00134
N,X=list(map(int,input().split())) L=sorted(map(int,input().split()),reverse=True) mod=10**9+7 from collections import defaultdict D=defaultdict(int) D[1,L[0]]=1 for l in L[1:]: ND=defaultdict(int) for c,s in D: k=D[c,s] if s+l+c-1<=X: ND[c+1,s+l]=(ND[c+1,s+l]+k*(c+1))%mod ND[c,s]=(ND[c,s]+k*(s-c*(l-1)))%mod for i in range(1,min(X-s-c+2,l+1)): ND[c,s+i]=(ND[c,s+i]+k*2*c)%mod for i in range(1,min(X-s-c+3,l+1)): ND[c-1,s+i]=(ND[c-1,s+i]+k*(c-1)*(l-i+1))%mod D=ND print((D[1,X]))
N,X=list(map(int,input().split())) L=sorted(map(int,input().split()),reverse=True) mod=10**9+7 D=[[0]*(X+1) for i in range(N//2+2)] D[1][L[0]]=1 for l in L[1:]: ND=[[0]*(X+1) for i in range(N//2+1)] for c in range(1,N//2+1): for s in range(X+1): if D[c][s]==0: continue k=D[c][s] if s+l+c<=X and c+1<=N//2: ND[c+1][s+l]=(ND[c+1][s+l]+k*(c+1))%mod ND[c][s]=(ND[c][s]+k*(s-c*(l-1)))%mod for i in range(1,min(X-s-c+2,l+1)): ND[c][s+i]=(ND[c][s+i]+k*2*c)%mod if c==1: continue for i in range(1,min(X-s-c+3,l+1)): ND[c-1][s+i]=(ND[c-1][s+i]+k*(c-1)*(l-i+1))%mod D=ND print((D[1][X]))
p02810
#!/usr/bin/env python3 # DSL_2_H: RMQ and RAQ # Range Minimum Query and Range Add Query # Lazy propagate segment tree from array import array import sys class SegmentTree: MAXV = 1000 * 10**5 + 1 def __init__(self, n): size = 1 while size < n: size *= 2 self.size = 2*size - 1 # self.data = [0] * self.size # self.lazy = [0] * self.size self.data = array('i', [0] * self.size) self.lazy = array('i', [0] * self.size) def add(self, lo, hi, v): def _add(r, i, j, lz): left, right = r*2 + 1, r*2 + 2 if lazy[r]: lz += lazy[r] lazy[r] = 0 if j < lo or i > hi: if lz: data[r] += lz if i < j: lazy[left] += lz lazy[right] += lz elif lo <= i and j <= hi: lz += v if lz: data[r] += lz if i < j: lazy[left] += lz lazy[right] += lz else: mid = (i + j) // 2 lv = _add(left, i, mid, lz) rv = _add(right, mid+1, j, lz) if lv < rv: data[r] = lv else: data[r] = rv return data[r] lazy = self.lazy data = self.data _add(0, 0, self.size//2, 0) def min(self, lo, hi): def _min(r, i, j, lz): left, right = r*2 + 1, r*2 + 2 if lazy[r]: lz += lazy[r] lazy[r] = 0 if lz: data[r] += lz if j < lo or i > hi: if lz and i < j: lazy[left] += lz lazy[right] += lz return self.MAXV elif lo <= i and j <= hi: if lz and i < j: lazy[left] += lz lazy[right] += lz return data[r] else: mid = (i + j) // 2 lv = _min(left, i, mid, lz) rv = _min(right, mid+1, j, lz) if lv < rv: return lv else: return rv lazy = self.lazy data = self.data return _min(0, 0, self.size//2, 0) def run(): n, q = [int(i) for i in input().split()] tree = SegmentTree(n) ret = [] for line in sys.stdin: com, *args = line.split() if com == '0': s, t, x = list(map(int, args)) tree.add(s, t, x) elif com == '1': s, t = list(map(int, args)) ret.append(tree.min(s, t)) sys.stdout.write("\n".join([str(i) for i in ret])) sys.stdout.write("\n") if __name__ == '__main__': run()
#!/usr/bin/env python3 # DSL_2_H: RMQ and RAQ # Range Minimum Query and Range Add Query # Lazy propagate segment tree from array import array import sys class SegmentTree: MAXV = 1000 * 10**5 + 1 def __init__(self, n): size = 1 while size < n: size *= 2 self.size = 2*size - 1 self.data = array('i', [0] * self.size) self.lazy = array('i', [0] * self.size) def add(self, lo, hi, v): def _add(r, i, j, lz): left, right = r*2 + 1, r*2 + 2 if lazy[r]: lz += lazy[r] lazy[r] = 0 if lo <= i and j <= hi: lz += v if lz: data[r] += lz if i < j: lazy[left] += lz lazy[right] += lz else: mid = (i + j) // 2 if mid >= lo: lv = _add(left, i, mid, lz) else: lazy[left] += lz lv = data[left] + lazy[left] if mid < hi: rv = _add(right, mid+1, j, lz) else: lazy[right] += lz rv = data[right] + lazy[right] if lv < rv: data[r] = lv else: data[r] = rv return data[r] lazy = self.lazy data = self.data _add(0, 0, self.size//2, 0) def min(self, lo, hi): def _min(r, i, j, lz): left, right = r*2 + 1, r*2 + 2 if lazy[r]: lz += lazy[r] lazy[r] = 0 if lz: data[r] += lz if lo <= i and j <= hi: if lz and i < j: lazy[left] += lz lazy[right] += lz return data[r] else: mid = (i + j) // 2 if mid >= lo: lv = _min(left, i, mid, lz) else: lazy[left] += lz lv = self.MAXV if mid < hi: rv = _min(right, mid+1, j, lz) else: lazy[right] += lz rv = self.MAXV if lv < rv: return lv else: return rv lazy = self.lazy data = self.data return _min(0, 0, self.size//2, 0) def run(): n, q = [int(i) for i in input().split()] tree = SegmentTree(n) ret = [] for line in sys.stdin: com, *args = line.split() if com == '0': s, t, x = list(map(int, args)) tree.add(s, t, x) elif com == '1': s, t = list(map(int, args)) ret.append(tree.min(s, t)) sys.stdout.write("\n".join([str(i) for i in ret])) sys.stdout.write("\n") if __name__ == '__main__': run()
p02352
while 1: a=[i+1 for i in range(10)] try:b=list(map(int,input().split())) except:break for i in b:a.remove(i) print((['NO','YES'][sum([1 for i in a if sum(b[:2],i)<=20])/7>=0.5]))
while 1: a=[i+1 for i in range(10)] try:b=list(map(int,input().split())) except:break for i in b:a.remove(i) c=sum(b[:2]) print((['NO','YES'][sum([1 for i in a if c+i<=20])/7>=0.5]))
p00060
import sys for s in sys.stdin: C=[0]+[1]*10 a,b,c=list(map(int,s.split())) C[a]=0 C[b]=0 C[c]=0 if sum(C[:21-a-b])>=4:print("YES") else: print("NO")
import sys for s in sys.stdin: a,b,c=list(map(int,s.split())) x=20-a-b f=3 if x<a: f-=1 if x<b: f-=1 if x<c: f-=1 if x-f>=4:print("YES") else: print("NO")
p00060
N,K=list(map(int,input().split())) td=sorted([tuple(map(int,input().split())) for _ in range(N)],key=lambda x:-x[1]) answer=0 number=[] 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[index][0] not in number: number.append(td[index][0]) tempanswer=tempanswer+td[index][1]-afterpop.pop()-(len(number)-1)**2+(len(number))**2 answer=max(tempanswer,answer) index+=1 print(answer)
N,K=list(map(int,input().split())) td=sorted([tuple(map(int,input().split())) for _ in range(N)],key=lambda x:-x[1]) answer=0 number=set() afterpop=[] for i in range(K): answer+=td[i][1] if td[i][0] not in number: number.add(td[i][0]) else: afterpop.append(td[i][1]) answer+=(len(number))**2 index=K tempanswer=answer while index<N and afterpop: if td[index][0] not in number: number.add(td[index][0]) tempanswer=tempanswer+td[index][1]-afterpop.pop()-(len(number)-1)**2+(len(number))**2 answer=max(tempanswer,answer) index+=1 print(answer)
p03148
N,K=list(map(int,input().split())) l=[] # 寿司リスト。ただし,「おいしさ」を第1要素にする dj=[] # 寿司タプルをそのまま入れる s=set() for i in range(N): t,d=list(map(int,input().split())) l.append((d,t)) l.sort(reverse=True) ans=K**2 j=0 # 既に食べたことのある種類の寿司を更に食べた回数 for i in range(K): # i番目に食べる寿司について while l and l[0][1] in s: dj.append(l.pop(0)) if (l and dj and l[0][0]>=dj[0][0]-(2*K-1-2*j)) or not dj: ans+=l[0][0] s.add(l[0][1]) l.pop(0) else: ans+=dj[0][0]-(2*K-1-2*j) dj.pop(0) j+=1 print(ans)
N,K=list(map(int,input().split())) l=[] # 寿司リスト。ただし,「おいしさ」を第1要素にする m=[] # 寿司タプルをそのまま入れる s=set() for i in range(N): t,d=list(map(int,input().split())) l.append((d,t)) l.sort(reverse=True) ans=K**2 t=0 # 既に食べたことのある種類の寿司を更に食べた回数 i=0 # l内を走査する際の添字 j=0 # m内を操作する際の添え字 for _ in range(K): # _番目に食べる寿司について while i<N and l[i][1] in s: m.append(l[i]) # そのままmに追加する i+=1 # lの先頭の要素を削除せず, if (i<N and (m and j<len(m)) and l[i][0]>=m[j][0]-(2*K-1-2*t)) or (not m or j>=len(m)): ans+=l[i][0] s.add(l[i][1]) i+=1 else: ans+=m[j][0]-(2*K-1-2*t) j+=1 t+=1 print(ans)
p03148
from heapq import heappop, heappush from collections import defaultdict N, K = list(map(int, input().split())) X = [list(map(int, input().split())) for _ in range(N)] # Step 1: Choose greedy X.sort(key=lambda x: -x[1]) pq = [] chosen = defaultdict(int) cnt = 0 score = 0 for t, d in X[:K]: heappush(pq, (d, t)) cnt += 1 if chosen[t] == 0 else 0 chosen[t] += 1 score += d ans = score + cnt ** 2 # Step 2: Replace chosen items idx = K while pq: # Step 2.1 d_p, t_p = heappop(pq) if chosen[t_p] <= 1: continue chosen[t_p] -= 1 score -= d_p # Step 2.2 while idx < N and chosen[X[idx][0]] != 0: idx += 1 if idx == N: break cnt += 1 chosen[X[idx][0]] += 1 score += X[idx][1] ans = max(ans, score + cnt ** 2) print(ans)
from collections import defaultdict from heapq import heappop, heappush N, K = list(map(int, input().split())) X = [list(map(int, input().split())) for _ in range(N)] X.sort(key=lambda x: x[1]) pq = [] f_x = 0 ctr = defaultdict(int) appeared = 0 for _ in range(K): t, d = X.pop() heappush(pq, (d, t)) appeared += int(ctr[t] == 0) f_x += d ctr[t] += 1 res = f_x + appeared ** 2 while pq or X: while pq: d, t = heappop(pq) if ctr[t] > 1: ctr[t] -= 1 f_x -= d break if not pq: break while X: t_x, d_x = X.pop() if ctr[t_x] == 0: heappush(pq, (d_x, t_x)) f_x += d_x ctr[t_x] += 1 appeared += 1 res = max(res, f_x + appeared ** 2) break print(res)
p03148
import itertools n,k = list(map(int,input().split())) td = [] for i in range(n): td_tmp = list(map(int,input().split())) td.append(td_tmp) # 貪欲で td_comb = list(itertools.combinations(td, k)) ans = 0 for i in td_comb: tmp_ans = 0 cnt = 0 t_lst = [] for j in i: tmp_ans += j[1] if j[0] not in t_lst: cnt += 1 t_lst.append(j[0]) tmp_ans += cnt**2 ans = tmp_ans if tmp_ans>ans else ans print(ans)
N, K = list(map( int, input().split())) T = [(0,0)]*N for i in range(N): t, d = list(map( int, input().split())) T[i] = (d,t) T.sort( key= None, reverse = True) C = T[:K] AC = T[K:] kiso = 0 s = 0 S = [0]*(N+1) for i in range(K): d, t = T[i] kiso += d if S[t] == 0: S[t] = 1 s += 1 else: S[t] += 1 ans = kiso + s**2 C.sort() r = 0 for i in range(K): d, t = C[i] if S[t] >= 2: while r < N-K: if S[ AC[r][1]] == 0: S[t] -= 1 S[ AC[r][1]] += 1 s += 1 kiso -= d kiso += AC[r][0] r += 1 break r += 1 ans = max( ans, kiso + s**2) print( ans)
p03148
#from collections import deque,defaultdict printn = lambda x: print(x,end='') inn = lambda : int(input()) inl = lambda: list(map(int, input().split())) inm = lambda: map(int, input().split()) ins = lambda : input().strip() DBG = True # and False BIG = 10**18 R = 10**9 + 7 def ddprint(x): if DBG: print(x) n,k = inm() dt = [] for i in range(n): t,d = inm() dt.append((d,t)) dt.sort(reverse=True) a = dt[:k] # oisisa max, ignore variety vals = [z[0] for z in a] dsum = sum(vals) typs = set([z[1] for z in a]) ntyp = len(typs) mx = dsum+ntyp**2 # satisfy for a b = dt[k:] h = {} for d,t in b: if t in typs: continue elif t not in h: h[t] = d else: h[t] = max(h[t],d) c = [h[t] for t in h] c.sort(reverse=True) # for types not in a, max oisisa h = {} for d,t in a: if t not in h: h[t] = d else: h[t] = max(h[t],d) for t in h: vals.remove(h[t]) vals.sort() # oisisa list for second or below for each type for i in range(min(len(vals),len(c))): dsum += c[i]-vals[i] ntyp += 1 mx = max(mx,dsum+ntyp**2) print(mx)
#from collections import deque,defaultdict printn = lambda x: print(x,end='') inn = lambda : int(input()) inl = lambda: list(map(int, input().split())) inm = lambda: map(int, input().split()) ins = lambda : input().strip() DBG = True # and False BIG = 10**18 R = 10**9 + 7 def ddprint(x): if DBG: print(x) n,k = inm() dt = [] for i in range(n): t,d = inm() dt.append((d,t)) dt.sort(reverse=True) a = dt[:k] # oisisa max, ignore variety vals = [z[0] for z in a] dsum = sum(vals) typs = set([z[1] for z in a]) ntyp = len(typs) mx = dsum+ntyp**2 # satisfy for a b = dt[k:] h = {} for d,t in b: if t in typs: continue elif t not in h: h[t] = d else: h[t] = max(h[t],d) c = [h[t] for t in h] c.sort(reverse=True) # for types not in a, max oisisa h = {} for d,t in a: if t not in h: h[t] = d else: h[t] = max(h[t],d) vals = [] for d,t in a: if t in h and d==h[t]: del h[t] else: vals.append(d) vals.sort() # oisisa list for second or below for each type for i in range(min(len(vals),len(c))): dsum += c[i]-vals[i] ntyp += 1 mx = max(mx,dsum+ntyp**2) print(mx)
p03148
N, K = list(map(int, input().split())) sushi = [] for i in range(N): s = list(map(int, input().split())) sushi.append(s) sushi.sort(key=lambda x: x[1], reverse=True) def find_next(start, curr, point, tlist, tcount): if start == N: return [point, curr] max_c = curr max_p = point for s in sushi[start:]: if tlist[s[0]] > 0: continue for ri in range(len(curr) - 1, -1, -1): r = curr[ri] if tlist[r[0]] >= 2: c2 = [c for c in curr] t2 = [t for t in tlist] del c2[ri] c2.append(s) t2[r[0]] -= 1 t2[s[0]] = 1 p2 = point - r[1] + s[1] + (tcount + 1) * (tcount + 1) - tcount * tcount np, pc = find_next(start + 1, c2, p2, t2, tcount + 1) if np > max_p: max_p = np max_c = pc return [max_p, max_c] return [max_p, max_c] result = sushi[0: K] type_count = [0] * (N + 1) for r in result: type_count[r[0]] += 1 type_num = 0 for t in type_count: if t > 0: type_num += 1 point = type_num * type_num for r in result: point += r[1] ans_p, ans_c = find_next(K, result, point, type_count, type_num) print(ans_p)
N, K = list(map(int, input().split())) sushi = [] for i in range(N): s = list(map(int, input().split())) sushi.append(s) sushi.sort(key=lambda x: x[1], reverse=True) # pick from first point = 0 neta_set = set() removable_idx = list() for i in range(K): s = sushi[i] point += s[1] if s[0] not in neta_set: neta_set.add(s[0]) else: removable_idx.append(i) point += len(neta_set) **2 max_point = point # pick latest for s in sushi[K:]: if len(removable_idx) == 0: break if s[0] in neta_set: continue idx = removable_idx[-1] count = len(neta_set) point += s[1] - sushi[idx][1] point += (count + 1) ** 2 - count ** 2 neta_set.add(s[0]) removable_idx = removable_idx[:-1] if point > max_point: max_point = point print(max_point)
p03148
# D - Various Sushi import sys from collections import defaultdict import heapq readline = sys.stdin.readline dd = defaultdict(list) N, K = list(map(int, readline().split())) for i in range(N): t, d = list(map(int, readline().split())) heapq.heappush(dd[t], d*-1) dd = list(dd.values()) dd.sort() ans = 0 fix = 0 var = [] tmp_max = 0 for i in range(len(dd)): fix += heapq.heappop(dd[i]) * -1 for _ in range(K-(i+1)): if len(dd[i]) == 0: break tmp = heapq.heappop(dd[i]) * -1 heapq.heappush(var, tmp) while len(var) > K-(i+1) and len(var) > 0: heapq.heappop(var) if len(var) == K-(i+1): ans = max(ans , fix+sum(var) + (i+1)**2) print(ans)
# D - Various Sushi import sys from collections import defaultdict import heapq readline = sys.stdin.readline dd = defaultdict(list) N, K = list(map(int, readline().split())) for i in range(N): t, d = list(map(int, readline().split())) heapq.heappush(dd[t], d*-1) dd = list(dd.values()) dd.sort() ans = 0 fix = 0 var = [] len_var = 0 sum_var = 0 tmp_max = 0 for i in range(min(K, len(dd))): fix += heapq.heappop(dd[i]) * -1 for _ in range(len(dd[i])): tmp = heapq.heappop(dd[i]) * -1 heapq.heappush(var, tmp) len_var += 1 sum_var += tmp while len_var > K-(i+1) and len_var > 0: del_var = heapq.heappop(var) len_var -= 1 sum_var -= del_var if len_var == K-(i+1): ans = max(ans , fix+sum_var + (i+1)**2) print(ans)
p03148
from heapq import heappush, heappop import sys input = sys.stdin.readline N, K = list(map(int, input().split())) sushi = [None] * N for i in range(N): t, d = list(map(int, input().split())) sushi[i] = (d, t-1) sushi.sort(reverse=True) types = set() cand = [] s = x = 0 for d, t in sushi[:K]: if t in types: heappush(cand, d) else: types.add(t) x += 1 s += d ans = s + x*x for d, t in sushi[K:]: if t in types: continue if not cand: break dr = heappop(cand) s += d - dr types.add(t) x += 1 ans = max(ans, s + x*x) print(ans)
import sys input = sys.stdin.readline N, K = list(map(int, input().split())) sushi = [None] * N for i in range(N): t, d = list(map(int, input().split())) sushi[i] = (d, t) sushi.sort(reverse=True) types = set() cand = [] s = x = 0 for d, t in sushi[:K]: if t in types: cand.append(d) else: types.add(t) x += 1 s += d cand.sort(reverse=True) ans = s + x*x for d, t in sushi[K:]: if t in types: continue if not cand: break dr = cand.pop() s += d - dr types.add(t) x += 1 ans = max(ans, s + x*x) print(ans)
p03148
nk = input().split() n = int(nk[0]) k = int(nk[1]) dtlist = [] for i in range(n): td = input().split() t = int(td[0]) d = int(td[1]) dtlist.append((d, t)) dtlist.sort(reverse=True) t_to_maxidx = {} for idx, dt in enumerate(dtlist): d, t = dt if t not in t_to_maxidx: t_to_maxidx[t] = idx selected = [] count = 0 tcount = {} for t, idx in list(t_to_maxidx.items()): if count >= k: break selected.append(dtlist[idx]) count += 1 tcount[t] = 1 if t not in tcount else tcount[t] + 1 dtlist[idx] = None new_dtlist = [] for dt in dtlist: if dt is not None: new_dtlist.append(dt) dtlist = new_dtlist if k - count > 0: for i in range(k - count): dt = dtlist.pop(0) selected.append(dt) d, t = dt tcount[t] = 1 if t not in tcount else tcount[t] + 1 selected.sort() score = 0 for d, t in selected: score += d len_tcount = len(tcount) score += len_tcount * len_tcount for i in range(0, 2**32): next_score = score try: d_new, t_new = dtlist.pop(0) d_old, t_old = selected.pop(0) except IndexError: print(score) break next_score += d_new next_score -= d_old tcount[t_old] -= 1 if tcount[t_old] <= 1: next_score -= len_tcount * len_tcount len_tcount -= 1 next_score += len_tcount * len_tcount del tcount[t_old] if t_new not in tcount: next_score -= len_tcount * len_tcount len_tcount += 1 next_score += len_tcount * len_tcount tcount[t_new] = 1 else: tcount[t_new] += 1 if next_score <= score: print(score) break score = next_score
nk = input().split() n = int(nk[0]) k = int(nk[1]) dtlist = [] for i in range(n): td = input().split() t = int(td[0]) d = int(td[1]) dtlist.append((d, t)) dtlist.sort(reverse=True) t_to_maxidx = {} for idx, dt in enumerate(dtlist): d, t = dt if t not in t_to_maxidx: t_to_maxidx[t] = idx selected = [] count = 0 tcount = {} candidate = [(dtlist[idx][0], idx) for t, idx in list(t_to_maxidx.items())] candidate.sort(reverse=True) for d, idx in candidate: if count >= k: break d, t = dtlist[idx] selected.append(dtlist[idx]) count += 1 tcount[t] = 1 if t not in tcount else tcount[t] + 1 dtlist[idx] = None new_dtlist = [] for dt in dtlist: if dt is not None: new_dtlist.append(dt) dtlist = new_dtlist if k - count > 0: for i in range(k - count): dt = dtlist.pop(0) selected.append(dt) d, t = dt tcount[t] = 1 if t not in tcount else tcount[t] + 1 selected.sort() score = 0 for d, t in selected: score += d len_tcount = len(tcount) score += len_tcount * len_tcount for i in range(0, 2**32): next_score = score try: d_new, t_new = dtlist.pop(0) d_old, t_old = selected.pop(0) except IndexError: print(score) break next_score += d_new next_score -= d_old tcount[t_old] -= 1 if tcount[t_old] <= 1: next_score -= len_tcount * len_tcount len_tcount -= 1 next_score += len_tcount * len_tcount del tcount[t_old] if t_new not in tcount: next_score -= len_tcount * len_tcount len_tcount += 1 next_score += len_tcount * len_tcount tcount[t_new] = 1 else: tcount[t_new] += 1 if next_score <= score: print(score) break score = next_score
p03148
import sys input = sys.stdin.readline N, K = list(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 for i in range(1,min(K,len(y))+1): ans = max(ans, sum(y[:i])+sum(x[:max(0,K-i)])+i*i) print(ans)
import sys input = sys.stdin.readline N, K = list(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)
p03148
from itertools import accumulate N,K = list(map(int,input().split())) td = [tuple(map(int,input().split())) for i in range(N)] td = [(x[0]-1,x[1]) for x in td] td.sort(key=lambda x:-x[1]) t = [-1]*N for i in range(N): t[td[i][0]] = 0 tdK = 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 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) s = 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((l**2 + s)) else: s += d_rest_cum[-1] ans = l**2 + s for k in range(min(len(d_rest),len(d_candi))): ans = max((l+k+1)**2 + s + d_candi_cum[k] - d_rest_cum[k],ans) print(ans)
N,K = list(map(int,input().split())) td = [list(map(int,input().split())) for _ in range(N)] td.sort(key=lambda x:-x[1]) l,r = td[:K],td[K:] used_l = [0]*N for i in range(K): used_l[l[i][0]-1] += 1 remove = [] for i in range(K-1,-1,-1): if used_l[l[i][0]-1] >= 2: remove.append(l[i][1]) used_l[l[i][0]-1] -= 1 used_r = used_l.copy() add = [] for i in range(N-K): if used_r[r[i][0]-1] == 0: add.append(r[i][1]) used_r[r[i][0]-1] += 1 t = sum(used_l) ans = t**2 for i in range(K): ans += l[i][1] ref = ans for i in range(min(len(remove),len(add))): ref += (t+1)**2-t**2+add[i]-remove[i] t += 1 ans = max(ans,ref) print(ans)
p03148
from heapq import heappop, heappush, heapify N, K = list(map(int, input().split())) sushi = [] for _ in range(N): t, d = list(map(int, input().split())) sushi.append((-d, t)) heapify(sushi) maxs = [] rems = [] kinds = set() for _ in range(K): d, t = heappop(sushi) if t in kinds: heappush(rems, -d) else: maxs.append(-d) kinds.add(t) ans = sum(maxs) + sum(rems) + len(kinds)**2 while True: if not sushi or not rems: break d, t = heappop(sushi) if t in kinds: continue else: heappop(rems) maxs.append(-d) kinds.add(t) ans = max(ans, sum(maxs) + sum(rems) + len(kinds)**2) print(ans)
N, K = list(map(int, input().split())) sushi = [list(map(int, input().split())) for _ in range(N)] sushi.sort(key=lambda x: x[1], reverse=True) score = 0 remains = [] kinds = set() for t, d in sushi[:K]: if t in kinds: remains.append(d) kinds.add(t) score += d score += len(kinds)**2 test = score for t, d in sushi[K:]: if not remains: break if t in kinds: continue kinds.add(t) rm = remains.pop() test = test + (d - rm) + (len(kinds)*2 - 1) score = max(score, test) print(score)
p03148
n, k = list(map(int, input().split())) nai = [list(map(int, input().split())) for _ in range(n)] nai = sorted(nai, key=lambda x: -x[1]) ans = 0 aru = [] spe = set() m = 0 for i in range(k): anstmp = nai.pop(0) if(anstmp[0] not in spe): ans+=anstmp[1] spe.add(anstmp[0]) else: aru.append(anstmp[1]) m = ans + sum(aru) + len(spe)**2 for i in range(len(nai)): if(len(aru) == 0): break if(nai[i][0] not in spe): aru.pop() ans+=nai[i][1] spe.add(nai[i][0]) m = max(m, ans + sum(aru) + len(spe)**2) print(m)
n, k = list(map(int, input().split())) nai = [list(map(int, input().split())) for _ in range(n)] nai = sorted(nai, key=lambda x: -x[1]) ans = 0 aru = [] spe = set() m = 0 for i in range(k): anstmp = nai.pop(0) if(anstmp[0] not in spe): ans+=anstmp[1] spe.add(anstmp[0]) else: aru.append(anstmp[1]) sumaru = sum(aru) m = ans + sumaru + len(spe)**2 for i in range(len(nai)): if(len(aru) == 0): break if(nai[i][0] not in spe): sumaru-=aru.pop() ans+=nai[i][1] spe.add(nai[i][0]) m = max(m, ans + sumaru + len(spe)**2) print(m)
p03148
from collections import * n, k = list(map(int, input().split())) d, t = list(zip(*sorted(tuple(map(int, input().split()))[::-1] for _ in range(n))[::-1])) c = Counter(t[:k]) x = len(c) a = [sum(d[:k])] for i in range(k)[::-1]: if c[t[i]] > 1: c[t[i]] -= 1 a.append(a[-1] - d[i]) b = [0] for i in range(k, n): if c[t[i]] <= 0: c[t[i]] += 1 b.append(b[-1] + d[i]) r = 0 for i, (v, w) in enumerate(zip(a, b)): r = max(r, v+w+(x+i)**2) print(r)
n, k =list(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: if not a: break v -= a.pop() v += d s.add(t) r = max(r, len(s)**2+v) print(r)
p03148
N,K = list(map(int,input().split())) X = [] for i in range(N): t,d = list(map(int,input().split())) X.append((d,t)) X.sort(reverse=True) p,v = 0,set([]) pp = [] for i in range(K): p += X[i][0] if X[i][1] not in v: v.add(X[i][1]) else: pp.append((X[i][0],X[i][1])) Ans = p + len(v)**2 ans = Ans for i in range(K,N): if X[i][1] not in v and len(pp)>0: temp = pp[-1] pp = pp[:len(pp)-1] ans = ans - temp[0] + X[i][0] - len(v)**2 + (len(v)+1)**2 v.add(X[i][1]) Ans = max(Ans,ans) print(Ans)
# Python3 (3.4.3) import sys input = sys.stdin.readline # ------------------------------------------------------------- # function # ------------------------------------------------------------- # ------------------------------------------------------------- # main # ------------------------------------------------------------- N,K = list(map(int,input().split())) TD = [tuple(map(int,input().split())) for _ in range(N)] # 美味しい順にソートしておく # t : ネタの種類 # d : 美味しさ基礎ポイント TD.sort(key=lambda x:x[1], reverse=True) # 美味しい順にK個食べた場合の満足ポイント ans = 0 s = set() # 食べたネタの集合 r = list() # すでに食べたネタ, あとで交換する用 for i in range(K): t,d = TD[i] ans += d if t not in s: s.add(t) # 食べたネタの種類の集合 else: r.append(TD[i]) ans += len(s)**2 Ans = ans # 美味しい順のK+1番目から, ネタの種類が増えるような操作を順番に試していく for i in range(K,N): t0,d0 = TD[i] # まだ食べてないネタ and 交換用の寿司があるなら if t0 not in s and len(r) > 0: # 交換用の寿司の一番美味しさ基礎ポイントが低いものを交換するのが最善 t1,d1 = r.pop() # 満足ポイントの再計算 ans = ans - d1 + d0 - len(s)**2 + (len(s)+1)**2 # 食べたネタの集合に追加 s.add(t0) # 満足度が大きくなったか都度確認 Ans = max(Ans,ans) print(Ans)
p03148
N,K = (int(x) for x in input().split()) t_arr = [0]*(N+1) d_arr = [0]*(N+1) for i in range(N): t,d = tuple(int(x) for x in input().split()) t_arr[i+1] = t d_arr[i+1] = d td_index = list(range(1,N+1)) td_index.sort(key=lambda x:d_arr[x], reverse=True) n_dm_set = set() small_arr = [] d_dm = 0 for i in td_index[:K]: t = t_arr[i] d = d_arr[i] if t in n_dm_set: small_arr.append(d) n_dm_set.add(t) d_dm += d current_max = len(n_dm_set)**2+d_dm bucket = [0]*(N+1) for t in n_dm_set: bucket[t] = -1 d_x = d_dm nt_x = len(n_dm_set) for i in td_index[K:]: t = t_arr[i] if bucket[t] != 0: continue d = d_arr[i] bucket[t] = d if len(small_arr) == 0: break d_x += d d_x -= small_arr[-1] small_arr = small_arr[:-1] nt_x += 1 current_max = max(current_max, nt_x**2+d_x) print(current_max)
N,K = (int(x) for x in input().split()) t_arr = [0]*(N+1) d_arr = [0]*(N+1) for i in range(N): t,d = tuple(int(x) for x in input().split()) t_arr[i+1] = t d_arr[i+1] = d td_index = list(range(1,N+1)) td_index.sort(key=lambda x:d_arr[x], reverse=True) n_dm_set = set() small_arr = [] d_dm = 0 for i in td_index[:K]: t = t_arr[i] d = d_arr[i] if t in n_dm_set: small_arr.append(d) n_dm_set.add(t) d_dm += d current_max = len(n_dm_set)**2+d_dm n_x_set = set(n_dm_set) d_x = d_dm nt_x = len(n_dm_set) for i in td_index[K:]: if not small_arr: break t = t_arr[i] d = d_arr[i] if t in n_x_set: continue n_x_set.add(t) d_x += d d_x -= small_arr.pop() nt_x += 1 current_max = max(current_max, nt_x**2+d_x) print(current_max)
p03148
import sys def r(n, k, sl): sl.sort(key=lambda x: -x[1]) tl, dl = list(zip(*sl)) gmk = set() ce = [] for s in sl[:k]: if s[0] in gmk: ce.append(s) gmk.add(s[0]) gop = sum(dl[:k]) bmk = max(len(set(tl)), k) gscr = len(gmk)**2 + gop ce.sort(key=lambda x: x[1]) for c in ce[:bmk-len(gmk)]: for s in sl[k:]: if s[0] in gmk: continue k += 1 gmk.add(s[0]) gop = gop - c[1] + s[1] nscr = len(gmk)**2 + gop gscr = max(gscr, nscr) break return gscr def main(): input = sys.stdin.readline n, k = list(map(int, input().split())) sl = [list(map(int, input().split())) for _ in range(n)] print((r(n, k, sl))) if __name__ == '__main__': main()
import sys def r(n, k, sl): sl.sort(key=lambda x: -x[1]) gmk = set() gop = 0 ce = [] for ti, di in sl[:k]: if ti in gmk: ce.append(di) gmk.add(ti) gop += di gscr = len(gmk)**2 + gop for ti, di in sl[k:]: if 0 >= len(ce): break if ti in gmk: continue gmk.add(ti) odi = ce.pop() gop = gop - odi + di nscr = len(gmk)**2 + gop gscr = max(gscr, nscr) return gscr def main(): input = sys.stdin.readline n, k = list(map(int, input().split())) sl = [tuple(map(int, input().split())) for _ in range(n)] print((r(n, k, sl))) if __name__ == '__main__': main()
p03148
ri = lambda: int(eval(input())) rl = lambda: list(map(int,input().split())) N,K=rl() td = [rl() for _ in range(N)] from operator import itemgetter key0 = itemgetter(0) key1 = itemgetter(1) td.sort(key=key1,reverse=True) netas = set() dup = [] for t,d in td[:K]: if t in netas: dup.append(d) else: netas.add(t) score = len(netas)**2 + sum(map(key1,td[:K])) ans = score for t,d in td[K:]: if t not in netas and dup != []: netas.add(t) dup_ = dup.pop(-1) score += 2*len(netas)-1 + d - dup_ ans = max(ans,score) print(ans)
n,k = list(map(int,input().split())) top = [0]*n sub = [] for i in range(n): t,d = list(map(int,input().split())) t -=1 if top[t]==0: top[t]=d else: if top[t]>=d: sub.append(d) else: sub.append(top[t]) top[t]=d top.sort() top = top[::-1] res = [0] for i in range(n): if top[i]!=0: res.append(res[-1]+top[i]) else: res.append(-1) sub.sort() sub = sub[::-1] w = [0] for i in range(len(sub)): w.append(w[-1]+sub[i]) tmp = 0 for i in range(1,k+1): if len(w)-1>=k-i and res[i]!=-1: tmp = max(res[i]+w[k-i]+i*i,tmp) print(tmp)
p03148
# -*- coding: utf-8 -*- def popMaxOishisa(sushis): t, d = sushis.pop() return t, d def popMinOishisa_nonUniqueNeta(sel_sushis): if len(sel_sushis["min"]) == 0: return -1, -1 t, d = min(list(sel_sushis["min"].items()), key=lambda i:i[1]) sel_sushis[t].pop() if len(sel_sushis[t]) == 1: sel_sushis["min"].pop(t) else: sel_sushis["min"][t] = sel_sushis[t][-1] return t, d def popMaxOishisa_uniqueNeta(sushis, netas): t, d = -1, -1 while True: t, d = sushis.pop() if not t in netas: break return t, d n, k = list(map(int, input().split())) # Store data sushis = [] neta_set = set() sel_sushis = {} for i in range(n): t, d = list(map(int, input().split())) sushis.append((t,d)) neta_set.add(t) # Formatting sushis.sort(key=lambda i:i[1]) tMax = len(neta_set) # Select sushi set as maximum oishisa point sum_oishisa = 0 for i in range(k): t, d = popMaxOishisa(sushis) if not t in sel_sushis: sel_sushis[t] = [d] else: sel_sushis[t].append(d) sum_oishisa += d sel_sushis["min"] = {t:sel_sushis[t][-1] for t in sel_sushis if len(sel_sushis[t]) > 1} sel_neta = list(sel_sushis.keys()) tMin = len(sel_sushis) - 1 max_score = tMin**2 + sum_oishisa for nNeta in range(tMin+1, tMax + 1, 1): # Find sushi having minimum oishisa and being not unique for neta t1, d1 = popMinOishisa_nonUniqueNeta(sel_sushis) if t1 < 0: break sum_oishisa -= d1 # Find sushi having maximum oishisa and unique for neta t2, d2 = popMaxOishisa_uniqueNeta(sushis, sel_neta) sum_oishisa += d2 if not t2 in sel_sushis: sel_sushis[t2] = [d2] else: sel_sushis[t2].append(d2) sel_neta.append(t2) score = nNeta**2 + sum_oishisa if score > max_score: max_score = score print(max_score)
# -*- coding: utf-8 -*- n, k = list(map(int, input().split())) # Store data sushis = [] neta_set = set() for i in range(n): t, d = list(map(int, input().split())) sushis.append((t,d)) neta_set.add(t) # Formatting sushis.sort(key=lambda i:i[1]) tMax = len(neta_set) # Select sushi set as maximum oishisa point sel_sushis = [] neta_set = set() sum_oishisa = 0 for i in range(k): t, d = sushis.pop() if t in neta_set: sel_sushis.append((t,d)) else: neta_set.add(t) sum_oishisa += d sel_sushis.sort(key=lambda i:i[1], reverse=True) tMin = len(neta_set) max_score = tMin**2 + sum_oishisa for nNeta in range(tMin+1, tMax + 1, 1): # Find sushi having minimum oishisa and being not unique for neta if len(sel_sushis) == 0: break t1, d1 = sel_sushis.pop() sum_oishisa -= d1 # Find sushi having maximum oishisa and unique for neta while True: t2, d2 = sushis.pop() if not t2 in neta_set: break sum_oishisa += d2 neta_set.add(t2) score = nNeta**2 + sum_oishisa if score > max_score: max_score = score print(max_score)
p03148
# -*- coding: utf-8 -*- import bisect import heapq import math import random import sys from collections import Counter, defaultdict, deque from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal from functools import lru_cache, reduce from itertools import combinations, combinations_with_replacement, product, permutations from operator import add, mul, sub sys.setrecursionlimit(100000) def read_int(): return int(input()) def read_int_n(): return list(map(int, input().split())) def read_float(): return float(input()) def read_float_n(): return list(map(float, input().split())) def read_str(): return input().strip() def read_str_n(): return list(map(str, input().split())) def error_print(*args): print(*args, file=sys.stderr) def mt(f): import time def wrap(*args, **kwargs): s = time.time() ret = f(*args, **kwargs) e = time.time() error_print(e - s, 'sec') return ret return wrap @mt def slv(N, K, TD): TD.sort(key=lambda x: x[1], reverse=True) c = Counter() base = 0 rc = [] for i in range(K): t, k = TD[i] c[t] += 1 base += k if c[t] > 1: rc.append((t, k)) mi = i ans = base + len(c)**2 while True: if len(rc) == 0: break rt, rk = rc.pop() for i in range(mi+1, len(TD)): if TD[i][0] not in c: c[TD[i][0]] += 1 c[rt] -= 1 base -= rk base += TD[i][1] mi = i ans = max(ans, base + len(c)**2) break return ans def main(): # N = read_int() N, K = read_int_n() TD = [read_int_n() for _ in range(N)] print(slv(N, K, TD)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- import bisect import heapq import math import random import sys from collections import Counter, defaultdict, deque from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal from functools import lru_cache, reduce from itertools import combinations, combinations_with_replacement, product, permutations from operator import add, mul, sub sys.setrecursionlimit(100000) def read_int(): return int(input()) def read_int_n(): return list(map(int, input().split())) def read_float(): return float(input()) def read_float_n(): return list(map(float, input().split())) def read_str(): return input().strip() def read_str_n(): return list(map(str, input().split())) def error_print(*args): print(*args, file=sys.stderr) def mt(f): import time def wrap(*args, **kwargs): s = time.time() ret = f(*args, **kwargs) e = time.time() error_print(e - s, 'sec') return ret return wrap @mt def slv(N, K, TD): TD.sort(key=lambda x: x[1], reverse=True) c = Counter() base = 0 rc = [] for i in range(K): t, k = TD[i] c[t] += 1 base += k if c[t] > 1: rc.append((t, k)) mi = i ans = [base + len(c)**2] while True: if len(rc) == 0: break rt, rk = rc.pop() for i in range(mi+1, len(TD)): if TD[i][0] not in c: c[TD[i][0]] += 1 c[rt] -= 1 base -= rk base += TD[i][1] mi = i ans.append(base + len(c)**2) break else: break return max(ans) def main(): # N = read_int() N, K = read_int_n() TD = [read_int_n() for _ in range(N)] print(slv(N, K, TD)) if __name__ == '__main__': main()
p03148
from heapq import heappop, heappush N, K = list(map(int, input().split())) td = sorted([list(map(int, input().split())) for _ in range(N)], key=lambda x: x[1], reverse=True) q = [] v = [] cnt = 0 for t, d in td[:K]: cnt += d if t in v: heappush(q, d) else: v.append(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.append(t) ans = max(ans, cnt) print(ans)
from heapq import heappop, heappush N, K = list(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)
p03148
N, K = list(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)
N, K = list(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)
p03148
from collections import defaultdict n, k = list(map(int, input().split())) sushi = [list(map(int, input().split())) for _ in range(n)] sushi.sort(key=lambda x: x[1]) t = defaultdict(int) x = list(range(n - 1, n - k - 1, -1)) z = [0] for i in range(n - k, n): t[sushi[i][0]] += 1 z[0] += sushi[i][1] y = [] yd = list(t.keys()) for i in range(n - k - 1, -1, -1): if sushi[i][0] not in yd: y.append(i) yd.append(sushi[i][0]) y = y[::-1] k = 1 for k in range(1, len(y) + 1): for i in range(len(x) - 1, -1, -1): xi = x[i] if t[sushi[xi][0]] > 1: t[sushi[xi][0]] -= 1 z.append(z[-1] - sushi[xi][1] + sushi[y[-k]][1]) x.pop(i) break p = len(list(t.keys())) ans = 0 for i in range(len(z)): ans = max(ans, z[i] + (p + i) ** 2) print(ans)
import heapq n, k = list(map(int, input().split())) sushi = [list(map(int, input().split())) for _ in range(n)] sushi.sort(key=lambda x: x[1]) t = {} x = [] z = 0 for i in range(n - 1, n - k - 1, -1): ti, di = sushi[i] if ti in list(t.keys()): heapq.heappush(x, di) t[ti] += 1 else: t[ti] = 1 z += di p = len(list(t.keys())) ans = z + p ** 2 for i in range(n - k - 1, -1, -1): if len(x) == 0: break ti, di = sushi[i] if ti not in list(t.keys()): t[ti] = 1 z += di - heapq.heappop(x) p += 1 ans = max(ans, z + p ** 2) print(ans)
p03148
import sys, itertools #def input(): return sys.stdin.readline() def inpl(): return [int(i) for i in input().split()] N, K = inpl() Sushi = [] Neta = set() ans = 0 for _ in range(N): t, d = inpl() Sushi.append((d, t)) Sushi.sort(reverse = True) Db = [] Nd = [] for i in range(K): d, t = Sushi[i] if t not in Neta: Neta.add(t) ans += d else: Db.append(d) neta = len(Neta) Db = [0] + list(itertools.accumulate(Db)) Db.reverse() for i in range(N-K): d, t = Sushi[K+i] if t not in Neta: Neta.add(t) Nd.append(d) Nd = [0] + list(itertools.accumulate(Nd)) print((ans + max([(neta + i)**2 + j + k for i, (j, k) in enumerate(zip(Db, Nd))])))
import sys, itertools def input(): return sys.stdin.readline() def inpl(): return [int(i) for i in input().split()] N, K = inpl() Sushi = [] Neta = set() ans = 0 for _ in range(N): t, d = inpl() Sushi.append((d, t)) Sushi.sort(reverse = True) Db = [] Nd = [] for i in range(K): d, t = Sushi[i] if t not in Neta: Neta.add(t) ans += d else: Db.append(d) neta = len(Neta) Db = [0] + list(itertools.accumulate(Db)) Db.reverse() for i in range(N-K): d, t = Sushi[K+i] if t not in Neta: Neta.add(t) Nd.append(d) Nd = [0] + list(itertools.accumulate(Nd)) print((ans + max([(neta + i)**2 + j + k for i, (j, k) in enumerate(zip(Db, Nd))])))
p03148
from collections import defaultdict import heapq n, k = list(map(int, input().split())) sushi = [list(map(int, input().split())) for _ in range(n)] sushi.sort(key=lambda x: x[1]) kinds = defaultdict(int) eaten = [] ans = 0 for i in range(k): neta, point = sushi.pop() kinds[neta] += 1 ans += point heapq.heappush(eaten, [point, neta]) num_of_kinds = len(list(kinds.keys())) ans += num_of_kinds ** 2 candidate = ans for i in range(k): point, neta = heapq.heappop(eaten) if kinds[neta] == 1: continue kinds[neta] -= 1 while sushi: new_neta, new_point = sushi.pop() if kinds[new_neta] >= 1: continue else: break else: break kinds[new_neta] += 1 num_of_kinds += 1 delta = new_point - point + (2*num_of_kinds - 1) candidate += delta ans = max(ans, candidate) print(ans)
from collections import defaultdict import heapq import sys input = sys.stdin.readline n, k = list(map(int, input().split())) sushi = [list(map(int, input().split())) for _ in range(n)] sushi.sort(key=lambda x: x[1]) kinds = defaultdict(int) eaten = [] ans = 0 for i in range(k): neta, point = sushi.pop() kinds[neta] += 1 ans += point heapq.heappush(eaten, [point, neta]) num_of_kinds = len(list(kinds.keys())) ans += num_of_kinds ** 2 candidate = ans for i in range(k): point, neta = heapq.heappop(eaten) if kinds[neta] == 1: continue kinds[neta] -= 1 while sushi: new_neta, new_point = sushi.pop() if kinds[new_neta] >= 1: continue else: break else: break kinds[new_neta] += 1 num_of_kinds += 1 delta = new_point - point + (2*num_of_kinds - 1) candidate += delta ans = max(ans, candidate) print(ans)
p03148
N,K = list(map(int,input().split())) td = sorted([list(map(int,input().split())) for _ in range(N)],key = lambda x: (-x[1],x[0])) head = [] no_head = [] is_used = [False]*(N+1) for t,d in td[:K]: if is_used[t]: no_head.append(d) else: head.append(d) is_used[t] = True unused_head = [] for t,d in td[K:]: if not is_used[t]: unused_head.append(d) is_used[t] = True n = min(len(no_head),len(unused_head)) ans = 0 sum_head = sum(head) l_head = len(head) l_no_head = len(no_head) for i in range(n+1): ans = max(ans,sum_head+sum(no_head[:l_no_head-i])+sum(unused_head[:i]) + (l_head+i)**2) print(ans)
N,K = list(map(int,input().split())) td = sorted([list(map(int,input().split())) for _ in range(N)],key = lambda x: (-x[1],x[0])) head = [] no_head = [] is_used = [False]*(N+1) for t,d in td[:K]: if is_used[t]: no_head.append(d) else: head.append(d) is_used[t] = True unused_head = [] for t,d in td[K:]: if not is_used[t]: unused_head.append(d) is_used[t] = True n = min(len(no_head),len(unused_head)) sum_head = sum(head) sum_no_head = sum(no_head) sum_unused_head = 0 l_head = len(head) l_no_head = len(no_head) ans = sum_head + sum_no_head + l_head ** 2 for i in range(n): sum_no_head -= no_head[-1-i] sum_unused_head += unused_head[i] ans = max(ans,sum_head+sum_no_head+sum_unused_head + (l_head+i+1)**2) print(ans)
p03148
N,K = list(map(int,input().split())) td = sorted([list(map(int,input().split())) for _ in range(N)],key = lambda x: (-x[1],x[0])) head = [] no_head = [] is_used = [False]*(N+1) for t,d in td[:K]: if is_used[t]: no_head.append(d) else: head.append(d) is_used[t] = True unused_head = [] for t,d in td[K:]: if not is_used[t]: unused_head.append(d) is_used[t] = True n = min(len(no_head),len(unused_head)) sum_head = sum(head) sum_no_head = sum(no_head) sum_unused_head = 0 l_head = len(head) l_no_head = len(no_head) ans = sum_head + sum_no_head + l_head ** 2 for i in range(n): sum_no_head -= no_head[-1-i] sum_unused_head += unused_head[i] ans = max(ans,sum_head+sum_no_head+sum_unused_head + (l_head+i+1)**2) print(ans)
N,K = list(map(int,input().split())) TD = [list(map(int,input().split())) for _ in [0]*N] TD.sort(key=lambda x:(-x[1],x[0])) use = TD[:K] var = set() lock = [] unlock = [] for t,d in use: if t in var: unlock.append(d) else: var.add(t) lock.append(d) unlock.sort(reverse=True) Dscore = sum(lock) + sum(unlock) v = len(var) Vscore = v*v ans = Dscore + Vscore unused = TD[K:][::-1] while unlock and unused: t,d = unused.pop() if t in var: continue trash = unlock.pop() var.add(t) lock.append(d) v += 1 Dscore += d - trash Vscore = v*v ans = max(ans,Dscore + Vscore) print(ans)
p03148
import itertools import operator N, K = list(map(int, input().split())) sushi = [tuple([i] + [int(x) for x in input().split()]) for i in range(N)] sushi.sort(key=operator.itemgetter(2), reverse=True) from collections import OrderedDict, deque, Counter left = OrderedDict((x[0], x) for x in sushi) base = 0 choosen = [] choosen_kind = set() for x in sushi: i, t, _ = x if t not in choosen_kind: choosen.append(x) choosen_kind.add(t) del left[i] choosen.sort(key=operator.itemgetter(2), reverse=True) choosen = choosen[:K] base = sum(d for _,_,d in choosen) kinds = len(choosen) tl = list(itertools.islice(list(left.values()), K)) fixed = tl[:K - len(choosen)] cands = tl[K - len(choosen):] base += sum(d for _,_,d in fixed) score = base + kinds**2 if cands: comp = [] while cands and cands[0][2] > choosen[-1][2]: base_n = base base_n -= choosen[-1][2] base_n += cands[0][2] kinds_n = kinds - 1 score_n = base_n + kinds_n**2 if score_n > score: choosen = choosen[:-1] fixed += cands[0] cands = cands[1:] base, kinds, score = base_n, kinds_n, score_n else: break print(score)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from itertools import islice import operator N, K = list(map(int, input().split())) sushi = [tuple([i] + [int(x) for x in input().split()]) for i in range(N)] sushi.sort(key=operator.itemgetter(2), reverse=True) from collections import OrderedDict, deque, Counter left = OrderedDict((x[0], x) for x in sushi) base = 0 choosen = [None] * N choosen_kind = set() ci = 0 for x in sushi: i, t, _ = x if t not in choosen_kind: choosen[ci] = x ci += 1 choosen_kind.add(t) del left[i] choosen = choosen[:min(ci, K)] base = sum(d for _,_,d in choosen) kinds = len(choosen) cands = islice(list(left.values()), K) fixed = islice(cands, K - len(choosen)) base += sum(d for _,_,d in fixed) score = base + kinds**2 for cand in cands: if cand[2] <= choosen[-1][2]: break base_n = base base_n -= choosen[-1][2] base_n += cand[2] kinds_n = kinds - 1 score_n = base_n + kinds_n**2 if score_n > score: choosen.pop() base, kinds, score = base_n, kinds_n, score_n else: break print(score)
p03148
def takeSecond(elem): return elem[1] n,k = list(map(int,input().split())) sushi = [list(map(int,input().split())) for i in range(n)] sushi.sort(key=takeSecond,reverse=True) selected = sushi[:k] kindset = set([item[0] for item in selected]) startKindNum = len(kindset) score = startKindNum*startKindNum + sum([item[1] for item in selected]) maxscore = score front_pointer = k - 1 pointer = k for i in range(startKindNum+1,min([k+1,n+1])): #remove the smallest one that does not decrease kind for p in range(front_pointer,-1,-1): item = selected[p] flag = False for idx in range(p): if(selected[idx][0]==item[0]): score -= item[1] selected.remove(item) front_pointer = p - 1 flag = True break if(flag): break #add the largest one that add kind for j in range(pointer,n): if(sushi[j][0] not in kindset): selected.append(sushi[j]) kindset.add(sushi[j][0]) k += 1 pointer = j + 1 score += 2*startKindNum + 1 + sushi[j][1] if(score>maxscore): maxscore = score startKindNum += 1 break print(maxscore)
def takeSecond(elem): return elem[1] n,k = list(map(int,input().split())) sushi = [list(map(int,input().split())) for i in range(n)] sushi.sort(key=takeSecond,reverse=True) ''' selected = sushi[:k] kindset = set([item[0] for item in selected]) startKindNum = len(kindset) score = startKindNum*startKindNum + sum([item[1] for item in selected]) maxscore = score front_pointer = k - 1 pointer = k for i in range(startKindNum+1,min([k+1,n+1])): #remove the smallest one that does not decrease kind for p in range(front_pointer,-1,-1): item = selected[p] flag = False for idx in range(p): if(selected[idx][0]==item[0]): score -= item[1] selected.remove(item) front_pointer = p - 1 flag = True break if(flag): break #add the largest one that add kind for j in range(pointer,n): if(sushi[j][0] not in kindset): selected.append(sushi[j]) kindset.add(sushi[j][0]) k += 1 pointer = j + 1 score += 2*startKindNum + 1 + sushi[j][1] if(score>maxscore): maxscore = score startKindNum += 1 break ''' kindset = set([]) score = 0 extras = [] for item in sushi[:k]: if item[0] in kindset: extras.append(item[1]) else: kindset.add(item[0]) score += item[1] score += len(kindset)**2 maxscore = score for item in sushi[k:]: if not extras: break if item[0] in kindset: continue score += (item[1] - extras.pop()) + 2*len(kindset) + 1 kindset.add(item[0]) #print(score) if score > maxscore: maxscore = score print(maxscore)
p03148
from heapq import heappush, heappop N, K = list(map(int, input().split())) log = [0]*N pre = [] ls = [] for i in range(N): t, d = list(map(int, input().split())) t = t-1 heappush(ls,(-d,t)) v = 0 n = 0 for i in range(K): d, t = heappop(ls) d = -d log[t] += 1 v += d if log[t]>1: heappush(pre,(d,t)) else: n += 1 v += n*n ans = v while ls and pre: d, t = heappop(ls) if log[t]>0: continue log[t] += 1 d = -d pv = v x, y = heappop(pre) v -= x v += d v += 2*n+1 n += 1 if ans<v: ans = v print(ans)
from heapq import heappush, heappop N, K, *L = list(map(int, open(0).read().split())) ls = [] for t,d in zip(*[iter(L)]*2): ls += [(d,t)] used = [] cnt = {} hq = [] S = set() ls.sort(reverse=True) m = 0 for i in range(K): d,t = ls[i] cnt[t] = cnt.get(t,0)+1 m += d if cnt[t]>1: heappush(used,(d,t)) S.add(t) m += len(S)**2 for i in range(K,N): d,t = ls[i] if t not in S: heappush(hq,(-d,t)) ans = m while used: d,t = heappop(used) while hq: if hq[0][1] not in S: break heappop(hq) else: break m -= d n,s = heappop(hq) m += -n+2*len(S)+1 ans = max(ans,m) S.add(s) print(ans)
p03148
from heapq import heappush, heappop N, K, *L = list(map(int, open(0).read().split())) ls = [] for t,d in zip(*[iter(L)]*2): ls += [(d,t)] used = [] cnt = {} hq = [] S = set() ls.sort(reverse=True) m = 0 for i in range(K): d,t = ls[i] cnt[t] = cnt.get(t,0)+1 m += d if cnt[t]>1: heappush(used,(d,t)) S.add(t) m += len(S)**2 for i in range(K,N): d,t = ls[i] if t not in S: heappush(hq,(-d,t)) ans = m while used: d,t = heappop(used) while hq: if hq[0][1] not in S: break heappop(hq) else: break m -= d n,s = heappop(hq) m += -n+2*len(S)+1 ans = max(ans,m) S.add(s) print(ans)
from heapq import heappush, heappop N, K, *L = list(map(int, open(0).read().split())) ls = [] for t,d in zip(*[iter(L)]*2): ls += [(d,t)] used = [] cnt = [0]*(N+1) hq = [] S = set() ls.sort(reverse=True) m = 0 for i in range(K): d,t = ls[i] cnt[t] += 1 m += d if cnt[t]>1: used.append(d) S.add(t) used.sort(reverse=True) m += len(S)**2 for i in range(K,N): d,t = ls[i] if t not in S: heappush(hq,(-d,t)) ans = [m] while used: d = used.pop() while hq: if hq[0][1] not in S: break heappop(hq) else: break m -= d n,s = heappop(hq) m += -n+2*len(S)+1 ans.append(m) S.add(s) print((max(ans)))
p03148
from collections import defaultdict from heapq import heappush, heappop N,K,*L = list(map(int, open(0).read().split())) dic = defaultdict(list) ls = [] for i,(t,d) in enumerate(zip(*[iter(L)]*2)): dic[t].append(d) heappush(ls,(-d,t)) S = set() pre = [] ans = 0 num = 0 for i in range(K): d,t = heappop(ls) ans -= d if t not in S: num += 1 S.add(t) else: heappush(pre,-d) ans += num*num if pre==[]: print(ans) exit() m = ans for i in range(N-K): d,t = heappop(ls) if t in S: continue S.add(t) m -= heappop(pre) m += -d+2*num+1 num += 1 ans = max(ans,m) if pre==[]: break print(ans)
N,K,*L = list(map(int, open(0).read().split())) ls = [] for i,(t,d) in enumerate(zip(*[iter(L)]*2)): ls.append((d,t)) ls.sort() S = set() pre = [] ans = 0 num = 0 for i in range(K): d,t = ls.pop() ans += d if t not in S: num += 1 S.add(t) else: pre.append(d) pre.sort(reverse=True) ans += num*num if pre==[]: print(ans) exit() m = ans for i in range(N-K): d,t = ls.pop() if t in S: continue S.add(t) m -=pre.pop() m += d+2*num+1 num += 1 ans = max(ans,m) if pre==[]: break print(ans)
p03148
#!/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 list(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 list(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()
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 list(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([-x for x in delicious_dq])) def pop(self): self.size -= 1 tmp = heappop(self.h) return list([-x for x in 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 list(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()
p03148
from operator import itemgetter from collections import Counter import heapq N, K = [int(v) for v in input().split()] sushi = [tuple(int(v) for v in input().split()) for i in range(N)] sushi = sorted(sushi, key=itemgetter(1), reverse=True) ate_list = sushi[:K] kind_counter = Counter([s[0] for s in ate_list]) kind_cnt = len(list(kind_counter)) kind_cnt_seq = kind_cnt ** 2 max_pt = sum([s[1] for s in ate_list]) + kind_cnt_seq if K >= N: print(max_pt) exit() # print(ate_list) waiting_sushi = [] wait_kind = [] for s in sushi[K:]: if kind_counter[s[0]]: # すでに食べてる種類 continue if not s[0] in wait_kind: waiting_sushi.append(s) wait_kind.append(s[0]) # 食べた種類を増やしていくフェーズ idx = K - 1 # print(waiting_sushi) curr_pt = max_pt for s in waiting_sushi: target = None for i in range(idx, -1, -1): # 1個しかないものは交換しない if kind_counter[ate_list[i][0]] > 1: target = ate_list[i] idx = i break if not target: break # 入れ替えして比較 n_kind_cnt_seq = ((kind_cnt + 1) ** 2) curr_pt = curr_pt - target[1] + s[1] + n_kind_cnt_seq - kind_cnt_seq kind_cnt_seq = n_kind_cnt_seq max_pt = max(curr_pt, max_pt) kind_counter[target[0]] -= 1 kind_cnt += 1 idx -= 1 # print(kind_cnt) print(max_pt)
from operator import itemgetter from collections import Counter N, K = [int(v) for v in input().split()] sushi = [tuple(int(v) for v in input().split()) for i in range(N)] sushi = sorted(sushi, key=itemgetter(1), reverse=True) # # kind_counter = Counter([s[0] for s in ate_list]) # kind_cnt = len(list(kind_counter)) ## # すでにでてきたかどうかがわかれば良いので Counter を使う必要はない # (数える必要ない) ## kind = set() can_converts = [] # 変更しても良いよリスト max_pt = 0 for i in range(K): if sushi[i][0] in kind: can_converts.append(sushi[i]) else: kind.add(sushi[i][0]) max_pt += sushi[i][1] max_pt += len(kind) ** 2 # 食べた種類を増やしていくフェーズ curr_pt = max_pt for s in sushi[K:]: if not can_converts: break if s[0] not in kind: target = can_converts.pop(-1) curr_pt = curr_pt - target[1] + s[1] - len(kind) ** 2 + (len(kind) + 1) ** 2 max_pt = max(max_pt,curr_pt) kind.add(s[0]) print(max_pt) # kind_cnt_seq = kind_cnt ** 2 # max_pt = sum([s[1] for s in ate_list]) + kind_cnt_seq # # if K >= N: # print(max_pt) # exit() # # waiting_sushi = [] # wait_kind = [] # for s in sushi[K:]: # if kind_counter[s[0]]: # すでに食べてる種類 # continue # # if not s[0] in wait_kind: # waiting_sushi.append(s) # wait_kind.append(s[0]) # # # 食べた種類を増やしていくフェーズ # idx = K - 1 # curr_pt = max_pt # for s in waiting_sushi: # target = None # for i in range(idx, -1, -1): # # 1個しかないものは交換しない # if kind_counter[ate_list[i][0]] > 1: # target = ate_list[i] # idx = i # break # # if not target: # break
p03148
import sys import heapq as h input=sys.stdin.readline N,K=list(map(int,input().split())) sushi=[[0,0] for i in range(0,N)] for i in range(0,N): t,k=list(map(int,input().split())) sushi[i][1]=t sushi[i][0]=k sushikind=[[] for i in range(0,N+1)] for i in range(0,N): sushikind[sushi[i][1]].append(sushi[i][0]) kindmax=[0 for i in range(0,N+1)] for i in range(0,N): if sushikind[i]: kindmax[i]=max(sushikind[i]) sushi.sort(reverse=True) sum=0 kind=[] kind=set(kind) extra=[] need=[] for i in range(0,K): sum+=sushi[i][0] kind.add(sushi[i][1]) if sushi[i][0]==kindmax[sushi[i][1]]: if sushi[i] in need: extra.append(sushi[i][0]) else: need.append(sushi[i]) else: extra.append(sushi[i][0]) set={i for i in range(1,N+1)} set-=kind appendix=[kindmax[i] for i in set if kindmax[i]!=0 ] extra.sort() appendix.sort(reverse=True) k=len(kind) first=k ans=k**2+sum for i in range(k,min(K,k+len(appendix))): k+=1 sum+=appendix[k-first-1]-extra[k-first-1] test=k**2+sum if test>ans: ans=test print(ans)
import sys import heapq as h input=sys.stdin.readline N,K=list(map(int,input().split())) sushi=[[0,0] for i in range(0,N)] for i in range(0,N): t,k=list(map(int,input().split())) sushi[i][1]=t sushi[i][0]=k sushikind=[[] for i in range(0,N+1)] for i in range(0,N): sushikind[sushi[i][1]].append(sushi[i][0]) kindmax=[0 for i in range(0,N+1)] for i in range(0,N): if sushikind[i]: kindmax[i]=max(sushikind[i]) sushi.sort(reverse=True) sum=0 kind=[] kind=set(kind) extra=[] flag=[0 for i in range(0,N+1)] for i in range(0,K): sum+=sushi[i][0] kind.add(sushi[i][1]) if sushi[i][0]==kindmax[sushi[i][1]]: if flag[sushi[i][1]]==1: extra.append(sushi[i][0]) else: flag[sushi[i][1]]=1 else: extra.append(sushi[i][0]) set={i for i in range(1,N+1)} set-=kind appendix=[kindmax[i] for i in set if kindmax[i]!=0 ] extra.sort() appendix.sort(reverse=True) k=len(kind) first=k ans=k**2+sum for i in range(k,min(K,k+len(appendix))): k+=1 sum+=appendix[k-first-1]-extra[k-first-1] test=k**2+sum if test>ans: ans=test print(ans)
p03148
n, k = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(n)] ab_s = sorted(ab, key=lambda x: x[1]) ab_r = list(reversed(ab_s)) t = [x[0] for x in ab_r] d = [x[1] for x in ab_r] t_set = len(set(t[:k])) d_sum = sum(d[:k]) res = [t_set**2 + d_sum] from collections import Counter t_cou = Counter(t[:k]) dp =[0]*(n+1) j_old = k-1 for i in t_cou: dp[i] = t_cou[i] for i in range(k,n): t_new = ab_r[i][0] if dp[t_new] ==0: for j in range(j_old,-1,-1): t_old = ab_r[j][0] if dp[t_old] <=1: pass else: dp[t_new] =1 dp[t_old] -=1 t_set +=1 d_sum = d_sum - ab_r[j][1] + ab_r[i][1] res.append(t_set**2 + d_sum) j_old = j-1 break j_old = -1 print((max(res)))
n, k = list(map(int, input().split())) ab = [list(map(int, input().split())) for _ in range(n)] ab_s = sorted(ab, key=lambda x: x[1]) ab_r = list(reversed(ab_s)) t = [x[0] for x in ab_r] d = [x[1] for x in ab_r] t_set = len(set(t[:k])) d_sum = sum(d[:k]) res = [t_set**2 + d_sum] from collections import Counter t_cou = Counter(t[:k]) dp =[0]*(n+1) j_old = k-1 for i in t_cou: dp[i] = t_cou[i] for i in range(k,n): t_new = ab_r[i][0] if dp[t_new] ==0: for j in range(j_old,-1,-1): t_old = ab_r[j][0] if dp[t_old] <=1: pass else: dp[t_new] =1 dp[t_old] -=1 t_set +=1 d_sum = d_sum - ab_r[j][1] + ab_r[i][1] res.append(t_set**2 + d_sum) j_old = j-1 break j_old = 0 print((max(res)))
p03148
N,K = list(map(int,input().split())) TDlist = [list(map(int,input().split())) for x in range(N)] TDlist.sort(key = lambda x: x[1],reverse=True) kinds = [] seconds = [] answer = 0 for x in TDlist[:K]: if not x[0] in kinds: kinds.append(x[0]) else: seconds.append(x[1]) answer += x[1] answer += len(kinds)**2 score = answer max_score = answer for x in TDlist[K:]: if seconds == []: break if x[0] in kinds: continue kinds.append(x[0]) y = seconds.pop() score += (x[1] - y) + (len(kinds)*2 -1) max_score = max(score,answer) answer = max(answer,max_score) print(answer)
N,K = list(map(int,input().split())) TDlist = [] for x in range(0,N): TDlist.append(list(map(int,input().split()))) TDlist= sorted(TDlist, key = lambda x: x[1],reverse=True) kinds = set() seconds = [] answer = 0 for x in TDlist[:K]: if not x[0] in kinds: kinds.add(x[0]) else: seconds.append(x[1]) answer += x[1] answer += len(kinds)**2 score = answer for x in TDlist[K:]: if seconds == []: break if x[0] in kinds: continue kinds.add(x[0]) y = seconds.pop() score += (x[1] - y) + (len(kinds)*2 -1) answer = max(score,answer) print(answer)
p03148
n,k=list(map(int,input().split())) inf=10**18 sushi=[[-inf] for _ in range(n)] for i in range(n): t,d=list(map(int,input().split())) sushi[t-1].append(d) for i in range(n): sushi[i].sort(reverse=True) sushi.sort(key=lambda x:x[0],reverse=True) q=[] res=0 for i in range(k): res+=sushi[i][0] for j in sushi[i][1:]: q.append(j) q.sort() cur=res res+=k**2 for var in range(1,k)[::-1]: a=q.pop() b=sushi[var][0] cur+=a-b res=max(res,cur+var**2) print(res)
n,k=list(map(int,input().split())) INF=10**18 sushi=[[-INF] for _ in range(n)] for _ in range(n): t,d=list(map(int,input().split())) sushi[t-1].append(d) for i in range(n): sushi[i].sort(reverse=True) sushi.sort(key=lambda x:x[0],reverse=True) q=[] res=0 for i in range(k): res+=sushi[i][0] for j in sushi[i][1:]: q.append(j) q.sort() cur=res res+=k**2 for var in range(1,k)[::-1]: a=q.pop() b=sushi[var][0] cur+=a-b res=max(res,cur+var**2) print(res)
p03148
N,K=list(map(int,input().split())) t=[0 for i in range(N)] d=[0 for i in range(N)] for i in range(N): t[i],d[i]=list(map(int,input().split())) D=dict() for i in range(N): if not(t[i] in D): D[t[i]]=[] D[t[i]].append((d[i],i)) E=[0 for i in range(N)] for key in D: D[key].sort(reverse=True) E[D[key][0][1]]=1 A=[] B=[] for i in range(N): if E[i]==1: A.append(d[i]) else: B.append(d[i]) A.sort(reverse=True) B.sort(reverse=True) X=len(A) Y=len(B) S=[0 for i in range(X+1)] T=[0 for i in range(Y+1)] for i in range(X): S[i+1]=A[i]+S[i] for i in range(Y): T[i+1]=B[i]+T[i] L=[] for i in range(1,K+1): if i<=X and K-i<=Y: L.append(S[i]+T[K-i]+i*i) print((max(L)))
N,K=list(map(int,input().split())) sushi=[] for i in range(N): t,d=list(map(int,input().split())) sushi.append((t,d)) sushi.sort(key=lambda x:(x[0],-x[1])) #print(sushi) X=[sushi[0][1]] Y=[] for i in range(1,N): if sushi[i-1][0]==sushi[i][0]: Y.append(sushi[i][1]) else: X.append(sushi[i][1]) X.sort(reverse=True) Y.sort(reverse=True) SX=[0] SY=[0] for i in X: SX.append(SX[-1]+i) for i in Y: SY.append(SY[-1]+i) ans=0 #print(X) #print(Y) #1<=x<len(X) #K-len(Y)<=x<= for x in range(max(1,K-len(Y)),min(len(SX),K+1)): ans=max(SX[x]+SY[K-x]+x*x,ans) print(ans)
p03148
def solve(): from collections import namedtuple from heapq import heappush, heappop from operator import attrgetter import sys input = sys.stdin.readline Sushi = namedtuple('Sushi', 'taste kind') n, k = list(map(int, input().split())) e = [] for _ in range(n): t, d = list(map(int, input().split())) e.append(Sushi(taste=d, kind=t - 1)) e.sort(key=attrgetter('taste'), reverse=True) b = e[:k] # 美味しさ降順k個 ret = 0 used = [False] * n # 選択されている種類 h = [] # 選択から外す候補 x = 0 # 暫定選択の種類数 for s in b: if used[s.kind]: heappush(h, s) else: used[s.kind] = True x += 1 ret += s.taste ret += pow(x, 2) # 種類ボーナス t = ret r = iter(e[k:]) # 交換で入れる候補 while h: rem = heappop(h) # 選択から外す t -= rem.taste for s in r: if used[s.kind]: continue used[s.kind] = True t += s.taste + x * 2 + 1 x += 1 ret = max(ret, t) break else: break return ret if __name__ == '__main__': print((solve()))
def solve(): from collections import deque, namedtuple from operator import attrgetter import sys input = sys.stdin.readline Sushi = namedtuple('Sushi', 'taste kind') n, k = list(map(int, input().split())) e = [] for _ in range(n): t, d = list(map(int, input().split())) e.append(Sushi(taste=d, kind=t - 1)) e.sort(key=attrgetter('taste'), reverse=True) ret = 0 used = [False] * n # 選択されている種類 q = deque() # 選択から外す候補,[high->low] x = 0 # 暫定選択の種類数 for s in e[:k]: # 美味しさ降順k個 if used[s.kind]: q.append(s) # 同じ種類の2個目以降のみ交換候補になる else: used[s.kind] = True x += 1 ret += s.taste ret += pow(x, 2) # 種類ボーナス t = ret r = iter(e[k:]) # 交換で入れる候補 while q: rem = q.pop() # 選択から外す t -= rem.taste for s in r: if used[s.kind]: continue used[s.kind] = True t += s.taste + x * 2 + 1 x += 1 ret = max(ret, t) break else: break return ret if __name__ == '__main__': print((solve())) # k個持っておいて、下位を交換する
p03148
def solve(): from collections import deque, namedtuple from operator import attrgetter import sys input = sys.stdin.readline Sushi = namedtuple('Sushi', 'taste kind') n, k = list(map(int, input().split())) e = [] for _ in range(n): t, d = list(map(int, input().split())) e.append(Sushi(taste=d, kind=t - 1)) e.sort(key=attrgetter('taste'), reverse=True) ret = 0 used = [False] * n # 選択されている種類 q = deque() # 選択から外す候補,[high->low] x = 0 # 暫定選択の種類数 for s in e[:k]: # 美味しさ降順k個 if used[s.kind]: q.append(s) # 同じ種類の2個目以降のみ交換候補になる else: used[s.kind] = True x += 1 ret += s.taste ret += pow(x, 2) # 種類ボーナス t = ret r = iter(e[k:]) # 交換で入れる候補 while q: rem = q.pop() # 選択から外す t -= rem.taste for s in r: if used[s.kind]: continue used[s.kind] = True t += s.taste + x * 2 + 1 x += 1 ret = max(ret, t) break else: break return ret if __name__ == '__main__': print((solve())) # k個持っておいて、下位を交換する
def main(): from heapq import heappush, heappop from operator import itemgetter import sys input = sys.stdin.readline N, K = list(map(int, input().split())) dd = [] for _ in range(N): t, d = list(map(int, input().split())) t -= 1 dd.append((d, t)) dd.sort(key=itemgetter(0), reverse=True) ret = 0 biggest = [-1] * N h = [] kinds = 0 for d, t in dd[:K]: ret += d if ~biggest[t]: if biggest[t] > d: heappush(h, d) else: heappush(h, biggest[t]) biggest[t] = d else: kinds += 1 ret += kinds * 2 - 1 biggest[t] = d ans = ret for d, t in dd[K:]: if ~biggest[t]: continue if not h: break kinds += 1 diff = d + kinds * 2 - 1 - h[0] ret += diff if ans < ret: ans = ret biggest[t] = d heappop(h) print(ans) if __name__ == '__main__': main()
p03148
from operator import itemgetter from functools import reduce N, K = list(map(int, input().split())) t, d = list(zip(*(list(map(int, input().split())) for _ in range(N)))) fn = itemgetter(0) fd = itemgetter(1) ss = sorted(zip(t, d), key=fd, reverse=True) netas = set() duplicates = [] for s in ss[:K]: if s[0] in netas: duplicates.append(s[1]) else: netas.add(s[0]) p = sum(map(fd, ss[:K])) + len(netas)**2 ans = p for s in ss[K:]: if s[0] not in netas and duplicates: netas.add(s[0]) duplicate = duplicates.pop() p += (s[1] - duplicate) + 2 * len(netas) - 1 ans = max(ans, p) print(ans)
from heapq import heappush, heappop N, K = list(map(int, input().split())) t, d = ( list(zip(*(list(map(int, input().split())) for _ in range(N)))) if N else ((), ()) ) # おいしさについて貪欲に寿司を食べたときの満足ポイントを求める # その後、種類ボーナスを1個ずつ増やしたときの満足ポイントをそれぞれ求め、 # それらの最大値を求める S = sorted(zip(d, t), reverse=True) q = [] v = set() s = 0 for D, T in S[:K]: s += D if T in v: heappush(q, D) else: v.add(T) s += len(v)**2 opt = s for D, T in S[K:]: if T not in v and q: z = heappop(q) s += D + 2 * len(v) + 1 - z v.add(T) opt = max(opt, s) ans = opt print(ans)
p03148
import heapq def main(): num_sushi, chose_num = list(map(int, input().split())) data = [list(map(int, input().split())) for i in range(num_sushi)] data.sort(key=lambda x: -x[1]) delicious_heap = [] count_d, count_n = 0, 0 neta_data = [0 for i in range(num_sushi + 1)] for i in range(chose_num): neta, oishisa = data[i] if neta_data[neta]: heapq.heappush(delicious_heap, oishisa) else: neta_data[neta] = 1 count_n += 1 count_d += oishisa ans = count_d + count_n ** 2 for i in range(chose_num, num_sushi): if len(delicious_heap) == 0: break neta, oishisa = data[i] if neta_data[neta]: continue neta_data[neta] = 1 count_n += 1 pop_oishisa = heapq.heappop(delicious_heap) count_d += oishisa - pop_oishisa ans = max(ans, count_d + count_n ** 2) print(ans) if __name__ == '__main__': main()
import heapq import sys input = sys.stdin.readline def main(): num_sushi, chose_num = list(map(int, input().split())) data = [list(map(int, input().split())) for i in range(num_sushi)] data.sort(key=lambda x: -x[1]) delicious_heap = [] count_d, count_n = 0, 0 neta_data = [0 for i in range(num_sushi + 1)] for i in range(chose_num): neta, oishisa = data[i] if neta_data[neta]: heapq.heappush(delicious_heap, oishisa) else: neta_data[neta] = 1 count_n += 1 count_d += oishisa ans = count_d + count_n ** 2 for i in range(chose_num, num_sushi): if len(delicious_heap) == 0: break neta, oishisa = data[i] if neta_data[neta]: continue neta_data[neta] = 1 count_n += 1 pop_oishisa = heapq.heappop(delicious_heap) count_d += oishisa - pop_oishisa ans = max(ans, count_d + count_n ** 2) print(ans) if __name__ == '__main__': main()
p03148
# -*- coding: utf-8 -*- import sys from heapq import heapify, heappush, heappop from collections import Counter def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(eval(input())) def MAP(): return list(map(int, input().split())) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 N, K = MAP() DT = [] tmp = [[] for i in range(N)] for i in range(N): t, d = MAP() DT.append((d, t)) DT.sort(reverse=1) que = [] C = Counter() dcnt = 0 # ポイント上位K個をまず取る for i in range(K): d, t = DT[i] dcnt += d C[t] += 1 heappush(que, (d, t)) heapify(que) tcnt = len(C) ans = dcnt + tcnt**2 for i in range(K, N): d2, t2 = DT[i] # 既に持っている種類ならスキップ if C[t2] > 0: continue tmp = [] while que: d, t = heappop(que) # 2つ以上ある種類が来たら交換候補 if C[t] >= 2: break else: tmp.append((d, t)) # 全部1種類ずつになったらもう種類数を増やせないので終了 if not que: break # この候補と交換してみる dcnt -= d dcnt += d2 C[t] -= 1 C[t2] += 1 tcnt += 1 ans = max(ans, dcnt + tcnt**2) # 今回使った分を含め、キューを元に戻す heappush(que, (d2, t2)) for d, t in tmp: heappush(que, (d, t)) print(ans)
# -*- coding: utf-8 -*- import sys from heapq import heapify, heappop def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(eval(input())) def MAP(): return list(map(int, input().split())) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') sys.setrecursionlimit(10 ** 9) INF = 10 ** 18 MOD = 10 ** 9 + 7 N, K = MAP() DT = [] tmp = [[] for i in range(N)] for i in range(N): t, d = MAP() DT.append((d, t)) DT.sort(reverse=1) que = [] D = {} dcnt = 0 # ポイント上位K個をまず取る for i in range(K): d, t = DT[i] dcnt += d # 種類tが1つ目 if t not in D: D[t] = d # 2つ目以降なら、最大のものはDに残して他はキューへ else: if D[t] < d: D[t], d = d, D[t] que.append((d, t)) heapify(que) tcnt = len(D) ans = dcnt + tcnt**2 for i in range(K, N): d2, t2 = DT[i] # 既に持っている種類ならスキップ if t2 in D: continue D[t2] = d2 tmp = [] # 全部1種類ずつならもう種類数を増やせないので終了 if not que: break d, t = heappop(que) # この候補と交換してみる dcnt -= d dcnt += d2 tcnt += 1 ans = max(ans, dcnt + tcnt**2) print(ans)
p03148