有一种有趣的字符串价值计算方式:统计字符串中每种字符出现的次数,然后求所有字符次数的平方和作为字符串的价值
例如: 字符串"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
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] freq = new int[26]; int i, k, s=0; String input = sc.nextLine(); k = sc.nextInt(); for (i=0; i<input.length(); ++i) freq[(int)(input.charAt(i)-'a')]++; while (k-- != 0) { i = maxElement(freq); freq[i]--; } for (i=0; i<26; ++i) s += freq[i]*freq[i]; System.out.println(s); } private static int maxElement(int[] array) { int i, maxIndex=0; for (i=1; i<array.length; ++i) maxIndex = array[i]>array[maxIndex] ? i : maxIndex; return maxIndex; } }
<?php$str= trim(fgets(STDIN));$number= trim(fgets(STDIN));$arr= array();for($i=0; $i< strlen($str); $i++) {$arr[] = $str[$i];}$newArr= array_count_values($arr);arsort($newArr);foreach($newArras$key=> $value) {$result[] = $value;}$i=1;while( $i<= $number) {$result[0] = max($result) -1;$i++;arsort($result);$result= array_values($result);//print_r($result);}$sum= 0;for($i=0; $i< count($result); $i++){$sum= $sum+ $result[$i]*$result[$i];}echo$sum;
// 我这个方法就是强行搞。。,每次找到count数组中最大的那一个,减去1,再k - - // 应该有更好的方法,这个方法确实蠢了点。。 import java.util.*; public class Main{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int k = sc.nextInt(); int count[] = new int[26]; for (int i = 0; i < s.length(); i++) { count[s.charAt(i)-'a']++; } while (k>0) { int max = getMax(count); count[max]--; k--; } int sum = 0; for (int i = 0; i < 26; i++) { sum += count[i]*count[i]; } System.out.println(sum); } private static int getMax(int[] count) { int max_index = 0; for (int i = 1; i < count.length; i++) { if (count[i] > count[max_index]) { max_index = i; } } return max_index; } }