A1002 A+B for Polynomials 多项式相加

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:

N1​​ aN1​​​​ N2​​ aN2​​​​ ... NK​​ aNK​​​​

where K is the number of nonzero terms in the polynomial, Ni​​ and aNi​​​​ (,) are the exponents and coefficients, respectively. It is given that 1,0.

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

思路:

•用数组a存储最后结果,注意数组初始化;

•分别输入A和B,加到一个全空a上;遍历整个a,计算出非空项的个数;

•循环输出,注意空格(Notice that there must be NO extra space at the end of each line)和精确度(Please be accurate to 1 decimal place)要求。

 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     int k1, k2, e1, e2,count = 0;
 5     double c1, c2;
 6     double a[1005] = {0.0};//a保存最后结果 注意初始化
 7     //输入A
 8     cin >> k1;
 9     for (int i = 0; i < k1; i++) {
10         cin >> e1 >> c1;
11         a[e1] = c1;
12     }
13     //输入B
14     cin >> k2;
15     for (int i = 0; i < k2; i++) {
16         cin >> e2 >> c2;
17         a[e2] += c2;
18     }
19     //循环遍历计算非空项的个数
20     for (int i = 1000; i >= 0; i--) {
21         if (a[i] != 0) count++;
22     }
23     //输出 注意空格和精确度要求
24     printf("%d", count);
25     for (int i = 1000; i >= 0; i--) {
26         if (a[i] != 0)
27             printf(" %d %.1lf", i, a[i]);
28     }
29     return 0;
30 }
作者:PennyXia
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/PennyXia/p/12285025.html