1002 A+B for Polynomials

PAT甲级真题练习1002

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000

主要注意几个特殊的测试case

1、输入的数据中含有未合并的多项式,例如

3 2 1.2 2 2.3 1 1.4

2 3 0.1 1 1.1

2、如果底数相加之后为0,则这组数据就应该丢弃,例如

input

1 2 1.2

1 2 -1.2

output

0

本人测试通过的代码:

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 #include <iomanip>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     int k;
11     constexpr int line = 2;
12     map<int, double> out;
13     int exp;
14     double coe;
15 
16     for (int i = 0; i < line; i++) {
17         cin >> k;
18         for (int j = 0; j < k; j++) {
19             cin >> exp >> coe;
20             auto p = out.find(exp);
21             if (p == out.end()) {
22                 out.insert({ exp,coe });
23             }
24             else {//相同指数
25                 p->second += coe;
26                 if (p->second == 0) {//底数为零的情况
27                     out.erase(exp);
28                 }
29             }
30         }
31     }
32 
33     cout << out.size();
34     for (auto i = out.rbegin(); i != out.rend(); i++) {
35         cout << ' ' << i->first << ' ' << fixed << setprecision(1) << i->second;
36     }
37     cout << endl;
38 }

 

posted @ 2021-03-07 17:15  行路难,多歧路  阅读(72)  评论(0编辑  收藏  举报