【PAT甲级】1002 A+B for Polynomials

题目链接1002 A+B for Polynomials

1 题目

This time, you are supposed to find A+B where A and B are two polynomials.

Input Specification

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
$K\ N_1\ a_{​N​1}​​​​ N_2\ a_{​N​2}​​​​...\ N_K​\ a_{​N​K}​​​​$
where $K$ is the number of nonzero terms in the polynomial, $N​_i$​​ and $a​_{N​i}​​​​(i=1,2,⋯,K)$ are the exponents and coefficients, respectively. It is given that
$1 ≤ K ≤ 10,0 ≤ N​_K​ ​< ⋯ < N_2 ​​< N​_1 ≤ 1000$.

Output Specification

For each test case you should output the sum of $A$ and $B$ in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.

Sample Input

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output

3 2 1.5 1 2.9 0 3.2

2 分析

这道题有几个点需要注意:

  • 处理输入数据方式和常规有一些区别
  • coefficients 为浮点数且为负数时也要输出
  • 输出要精确到小数点后一位
  • 最后没有空格

3 题解

#include <iostream>
#include <cstdio>
using namespace std;

const int maxn = 1e3 + 5;
double a[maxn] = {0};

int main(){
    #ifdef ONLINE_JUDGE
    #else
        freopen("input.txt", "r", stdin);
    #endif // ONLINE_JUDGE
    int k;
    cin >> k;
    for(int i = 0;i < k;i++){
        int exp;
        double coe;
        cin >> exp >> coe;
        a[exp] = coe;
    }
    cin >> k;
    for(int i = 0;i < k;i++){
        int exp;
        double coe;
        cin >> exp >> coe;
        a[exp] += coe;
    }
    int cnt = 0;
    for(int i = 0;i < maxn;i++){
        if(a[i]){
            cnt++;
        }
    }
    printf("%d", cnt);
    for(int i = maxn;i >= 0;i--){
        //负数也需要输出
        if(a[i] != 0){
            //cout << " " << i << " " << a[i];
            //coe精确到小数点后一位
            printf(" %d %.1f", i, a[i]);
        }
    }
    return 0;
}