这个采用hash表存放数据就好了,每次输入查询是否有存在的key,存在就将value累加到表中,最后输出表。

  • java
    import java.util.*;
    public class Main {
     public static void main(String agv[]) {
          Scanner scanner = new Scanner(System.in);
          int tableSize = scanner.nextInt();
          Map<Integer, Integer> table = new HashMap<>(tableSize);
          for (int i = 0; i < tableSize; i++) {
              int key = scanner.nextInt();
              int value = scanner.nextInt();
              if (table.containsKey(key)) {
                  table.put(key, table.get(key) + value);
              } else {
                  table.put(key, value);
              }
          }
           for (Integer key : table.keySet()) {
              System.out.println( key + " " + table.get(key));
          }
      }
    }