PAT A1002 A+B for Polynomials (25)

来源:互联网 发布:因为你是范晓萱 知乎 编辑:程序博客网 时间:2024/05/16 14:47

题目地址:https://www.patest.cn/contests/pat-a-practise/1002

题目描述:

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

输入格式(Input):

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 … NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000.

输出格式(Output):

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


题意:

给出两行,每行表示一个多项式:第一个数表示该多项式中系数非零项的项数,后面每两个数表示一项,这两个数分别表示该项的幂次和系数。试求两个多项式的和,并以与前面相同的格式输出结果。


解题思路:

步骤 1:令 double 型数组 p[ max_n ] 表示多项式,其中 p[ n ] 表示幂次为 n 的项的系数,初始值为 0 。令 int 型变量 count 表示系数非零项的个数,初值为 0
步骤 2:先按输入格式读入第一个多项式,再读入第二个多项式,并把对应系数直接加到第一个多项式上。
步骤 3:计算非零系数项的个数 count 并输出,然后按格式输出该多项式。

注意点:

  • 输出要按照幂次从大到小的顺序,格式上需要保留一位小数。
  • 题目的输入和输出都是系数非零项。
  • 在使用 count 计数时,要注意正负抵消的问题:两个多项式的某一个相同幂次的项刚好为相反数,相加之后就为 0 了。因此采用下面这个写法的,要注意 count 必须在两项相加之后再判断是否自减。

C++完整代码如下:

这里写代码片
0 0