import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 这种n没啥用 顶多在下面的循环里再加个判断 食之无味弃之可惜
        int n = in.nextInt();
        Map<Integer, Integer> map = new TreeMap<>();
        while (in.hasNextInt()) {
            int k = in.nextInt();
            int v = in.nextInt();
            map.put(k, map.getOrDefault(k, 0) + v);
        }
        for(Map.Entry entry : map.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}

更新时间: 2023-03-15 9:43

摸鱼中,更优雅的写法

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Map<Integer, Integer> treeMap = new TreeMap<>();
        while (n-- > 0) {
            final int key = in.nextInt();
            final int value = in.nextInt();
            treeMap.compute(key, (k, v) -> v == null ? value : v + value);
        }
        treeMap.forEach((k, v) -> System.out.printf("%s %s\n", k, v));
    }
}