HJ8题解 | #合并表记录# 这道题很好!
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <iostream> #include <map> using namespace std; void InsertValue(std::map<int, long long> &data, int &key, long long &value) { // map 该insert返回值为 pair<iterator,bool> auto it = data.insert(std::pair<int, long long>(key, value)); if (it.second == false) { // it.second == false 说明key已经存在 it.first->second += value; } // it.second == true 说明插入成功 } int main() { // int range: -2147483648 ~ 2147483647 // 11111111 * 100000 = 1111111100000 std::map<int, long long> data; // int 范围不够,所以用了 long long 类型 int inputNum = 0; cin >> inputNum; int key = 0; long long value = 0; while(inputNum--) { cin >> key; cin >> value; InsertValue(data, key, value); } for (auto it : data) { cout << it.first << " " << it.second << endl; } }#刷题#