题目 多项式加法。
想法 本以为要用数组来解,但是想一想光搜索就容易爆时间,我又不想自己写一个二叉排序树的算法。
这样一想,没有思路,我就去看题解了。
发现 map 正好是一个映射关系,恰好符合这道题的要求。
所以本题的解题思路就是,如果 first 对应的值存在就加上 second,对应的值不存在就存入,之后利用反向迭代器统计非零元个数,并输出结果。
最后输出应当使用 printf ,使用 cout 会爆流。
代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 #include <iostream> #include <map> using namespace std ;int main () { int a_count, b_count; map <int , double > p; cin >> a_count; for (int j = 0 ; j < a_count; ++j) { int exp ; double coe; cin >> exp >> coe; if (!p.insert(make_pair(exp , coe)).second ) { p[exp ] = p[exp ] + coe; } } cin >> b_count; for (int j = 0 ; j < b_count; ++j) { int exp ; double coe; cin >> exp >> coe; if (!p.insert(make_pair(exp , coe)).second ) { p[exp ] = p[exp ] + coe; } } int total_count = 0 ; for (map <int , double >::reverse_iterator iter = p.rbegin(); iter != p.rend(); iter++) { if ((*iter).second != 0 ) { total_count++; } } cout << total_count; for (map <int , double >::reverse_iterator iter = p.rbegin(); iter != p.rend(); iter++) { if ((*iter).second != 0 ) { printf (" %d %.1lf" , (*iter).first, (*iter).second); } } }