想复杂了
用不到 hashmap排序
数组排序就可以了
学到了 hashmap 按值 排序方法
import java.util.Scanner; import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int n = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); String words = sc.nextLine(); int [] freq = new int [26]; HashMap<Character, Integer> t = new HashMap<Character, Integer> (); for(char c: words.toCharArray()) { if(t.containsKey(c)) t.put(c,t.get(c)+1); else t.put(c,1); int index = c-'A'; freq[index]++; } //chushihua wanbi ArrayList<Map.Entry<Character, Integer>> l = new ArrayList(t.entrySet()); Collections.sort(l, new Comparator<Map.Entry<?, Integer>>(){ public int compare(Map.Entry<?, Integer> o2, Map.Entry<?, Integer> o1) { return o1.getValue().compareTo(o2.getValue()); }}); long sum = 0; for (int i=0; i<l.size();i++){ if(l.get(i).getValue()<=k) { k = k-l.get(i).getValue(); sum = sum + (long) l.get(i).getValue() *l.get(i).getValue(); } else{ sum = sum + (long) k *k; k=0; } } System.out.println(sum); } } }