题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<functional>
#include<vector>
#include<map>
using namespace std;
int main(){
int n, pow, cnt = 1, nums = 0;
double val;
map<int, double, greater<int>> hash1;
map<int, double, greater<int>> hash2;
cin >> n;
for(int i = 0;i < n;i++){
cin >> pow >> val;
hash1[pow] = val;
}
cin>>n;
for(int i = 0;i < n;i++){
cin >> pow >> val;
hash2[pow] = val;
}
nums = hash1.size();
for(auto item : hash2){
if(hash1.count(item.first) == 0){
hash1[item.first] = item.second;
nums++;
}
else {
hash1[item.first] += item.second;
if(hash1[item.first] == 0) nums--;
}
}
cout<<nums;
for(auto it : hash1){
if(it.second != 0){
printf(" %d %.1lf", it.first, it.second);
}
cnt++;
}
return 0;
}
解题思路:首先想到的方法是用数组直接存储,这样的话会浪费比较大的空间,用两个哈希表去存储值,然后遍历其中一个哈希表hash2,如果该元素在哈希表hash1中存在,则需要去进行加减,没有的话添加就好了。最后注意一点,两个哈希表中相同幂次然后系数互为相反数的时候相加之后为0,那么这部分是不能输出的。