PTA甲级——1002

1002 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:

$$
\begin{flalign}
K\ N_1\ a_{N_1}\ N_2\ a_{N_2}\ N_2\ a_{N_2}\ … N_k\ a_{N_k}\\
\end{flalign}
$$

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<⋯<N2<N1≤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:

1
2
2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

1
3 2 1.5 1 2.9 0 3.2

思路

​ 这道题目的大致意思就是:对两个多项式进行加法计算,然后给出2行数据,每一行的的第一个数表示这个多项式的项数,后面每组数分别表示一个项的系数和指数,比如案例表示的就是对2.4x^1^ + 3.2x^0^ 和 1.5x^2^ + 0.5x^1^ 进行加法操作。输出的话就是第一个数为项的个数,后面的话则是从大到小依次输出各个项的指数和系数。

​ 思路的话也就不言而喻,就是相同指数相加即可。

代码

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
#include <iostream>
using namespace std;
const int N = 1e3 + 10;
double st[N];
int count = 0;

int main()
{
int k1, k2;
cin >> k1;
for (int i = 1; i <= k1; i++) {
int x;
double y;
cin >> x >> y;
st[x] += y;
}
cin >> k2;
for (int i = 1; i <= k2; i++){
int x;
double y;
cin >> x >> y;
st[x] += y;
}

for(int i = 0; i < N; i++){
if(st[i] != 0) count++;
}

cout << count;
for (int i = N - 1; i >= 0; i--) {
if (st[i] != 0) {
// cout << " " << i << " " << st[i];
printf(" %d %.1lf", i,st[i]);
}
}
return 0;
}