有一种有趣的字符串价值计算方式:统计字符串中每种字符出现的次数,然后求所有字符次数的平方和作为字符串的价值
例如: 字符串"abacaba",里面包括4个'a',2个'b',1个'c',于是这个字符串的价值为4 * 4 + 2 * 2 + 1 * 1 = 21
牛牛有一个字符串s,并且允许你从s中移除最多k个字符,你的目标是让得到的字符串的价值最小。
输入包括两行,第一行一个字符串s,字符串s的长度length(1 ≤ length ≤ 50),其中只包含小写字母('a'-'z')。 第二行包含一个整数k(0 ≤ k ≤ length),即允许移除的字符个数。
输出一个整数,表示得到的最小价值
aba 1
2
s = list(input()) k = int(input()) dic = {} for i in range(len(s)): if s[i] not in dic: dic[s[i]] = 1 else: dic[s[i]] += 1 while k > 0: dic[ max(dic,key=dic.get) ] -=1 k -= 1 sum = 0 for value in dic.values(): sum += value * value print(sum)
import sys s=list(sys.stdin.readline().strip()) k=int(sys.stdin.readline().strip()) # dic={i:s.count(i) for i in s} lcount=[s.count(i) for i in set(s)] for i in range(k): index=lcount.index(max(lcount)) lcount[index]=max(lcount)-1 squresum=0 for j in range(len(lcount)): squresum+=lcount[j]**2 print(squresum)
s=list(input()) k=int(input()) ss=set(s) sum=0 cou=[] ##统计不同字符的个数 for item in ss: cou.append(s.count(item)) if k!=0: while sum!=k: #操作次数不为给定数 cou_max=max(cou) #字符个数最大值 cou[cou.index(cou_max)]-=1 #最大值个数减一 sum+=1 #操作次数加一 res=0 for x in cou: res+=x*x print(res) else: res=0 for x in cou: res+=x*x print(res)
from collections import Counter
string, k = input(), int(input())
arr = sorted(Counter(string).values())
for i in range(k):
arr[-1] -= 1
arr.sort()
print(sum(map(lambda c: c ** 2, arr)))
思路是不断将出现最多次的字符数量减1。
最后将所有字符出现次数平方和加起来。
将出现次数最多的字符数量减1后,该字符数量可能不是最多的了,所以要作下sort
操作,找到出现次数最多的那个。
# coding=utf-8 def fun(): s = raw_input() k = int(raw_input()) Alphabet = [0]*26 for i in range(len(s)): Alphabet[ord(s[i])-ord('a')] += 1 for i in range(k): Alphabet.sort() Alphabet[-1] -= 1 #每次移除出现最多次的字符 result = 0 for i in range(len(Alphabet)): result += Alphabet[i] * Alphabet[i] return result if __name__=='__main__': print(fun())