fork download
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Main {
  5.  
  6.  
  7. private static final char NEW_LINE = '\n';
  8.  
  9. public static void main(String[] args) {
  10.  
  11. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1024 * 1024);
  12.  
  13. int intchr;
  14. try {
  15. Map<Integer, Entry> map = new HashMap<Integer, Entry>();
  16. while ((intchr = reader.read()) != -1) {
  17. if (intchr == NEW_LINE || intchr == '\r') {
  18. if (map.isEmpty()) {
  19. continue;
  20. }
  21. printResult(writer, map, true);
  22. writer.write("\n");
  23. map = new HashMap<Integer, Entry>();
  24. continue;
  25.  
  26. }
  27.  
  28. Entry integer = map.get(intchr);
  29. if (integer == null) {
  30. integer = new Entry(intchr);
  31. map.put(intchr, integer);
  32. }
  33. integer.frequency++;
  34. }
  35. printResult(writer, map, false);
  36. writer.flush();
  37. } catch (IOException e) {
  38.  
  39. }
  40. }
  41.  
  42. private static void printResult(BufferedWriter writer, Map<Integer, Entry> map, boolean printLastN) throws IOException {
  43. Entry[] values = map.values().toArray(new Entry[map.size()]);
  44.  
  45. Arrays.sort(values, new Comparator<Entry>() {
  46. public int compare(Entry o1, Entry o2) {
  47. int compare = o1.compareTo(o2);
  48. if (compare == 0) {
  49. return o2.value - o1.value;
  50. }
  51. return compare;
  52. }
  53. });
  54.  
  55. for (int i = 0; i < values.length; i++) {
  56. Entry value = values[i];
  57. writer.write(String.valueOf(value.value));
  58. writer.write(" ");
  59. writer.write(String.valueOf(value.frequency));
  60.  
  61. if (i + 1 == values.length && !printLastN) {
  62. continue;
  63. }
  64. writer.write("\n");
  65. }
  66.  
  67. }
  68.  
  69. static class Entry implements Comparable<Entry> {
  70. int frequency;
  71. final int value;
  72.  
  73. Entry(int value) {
  74. this.value = value;
  75. }
  76.  
  77.  
  78. @Override
  79. public boolean equals(Object o) {
  80. if (this == o) return true;
  81. if (o == null || getClass() != o.getClass()) return false;
  82.  
  83. Entry entry = (Entry) o;
  84.  
  85. if (value != entry.value) return false;
  86.  
  87. return true;
  88. }
  89.  
  90. @Override
  91. public int hashCode() {
  92. return value;
  93. }
  94.  
  95. public int compareTo(Entry o) {
  96. return frequency - o.frequency;
  97. }
  98. }
  99.  
  100. }
  101.  
Success #stdin #stdout 0.03s 245632KB
stdin
AAABBC
122333
stdout
67 1
66 2
65 3

49 1
50 2
51 3