解题思路

  1. 使用Map数据结构存储index和value的对应关系
  2. 读取输入:
    • 首先读取记录数n
    • 然后读取n行index和value对
  3. 如果遇到相同的index,将value值累加
  4. 最后按index升序输出结果

代码

#include <iostream>
#include <map>
using namespace std;

int main() {
    int n;
    cin >> n;
    
    map<int, int> records;
    
    // 读取输入并合并
    for(int i = 0; i < n; i++) {
        int index, value;
        cin >> index >> value;
        records[index] += value;  // 自动处理重复的index
    }
    
    // 按序输出结果
    for(const auto& pair : records) {
        cout << pair.first << " " << pair.second << endl;
    }
    
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        // TreeMap自动按键排序
        TreeMap<Integer, Integer> records = new TreeMap<>();
        
        // 读取输入并合并
        for(int i = 0; i < n; i++) {
            int index = sc.nextInt();
            int value = sc.nextInt();
            records.put(index, records.getOrDefault(index, 0) + value);
        }
        
        // 输出结果
        for(Map.Entry<Integer, Integer> entry : records.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
}
n = int(input())
records = {}

# 读取输入并合并
for _ in range(n):
    index, value = map(int, input().split())
    records[index] = records.get(index, 0) + value

# 按序输出结果
for index in sorted(records.keys()):
    print(index, records[index])

算法及复杂度

  • 算法:使用有序映射表(Map)存储和合并数据
  • 时间复杂度: - 主要来自Map的插入和排序操作
  • 空间复杂度: - k为不同index的数量,最坏情况下为n