#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;
}
importjava.util.*;publicclassMain{publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);int n = sc.nextInt();// TreeMap自动按键排序TreeMap<Integer,Integer> records =newTreeMap<>();// 读取输入并合并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 _ inrange(n):
index, value =map(int,input().split())
records[index]= records.get(index,0)+ value
# 按序输出结果for index insorted(records.keys()):print(index, records[index])
算法及复杂度
算法:使用有序映射表(Map)存储和合并数据
时间复杂度:
O
(
n
log
n
)
\mathcal{O}(n\log n)
O(nlogn) - 主要来自Map的插入和排序操作
空间复杂度:
O
(
k
)
\mathcal{O}(k)
O(k) - k为不同index的数量,最坏情况下为n