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

K N1 aN1 *N2 *aN2 … NK aNK

where K is the number of nonzero terms in the polynomial, N**i and aNi (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

Code

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
41
42
43
44
45
#pragma once
#include <iostream>
#include <stack>

using namespace std;
//注意点
//coefficients可以是负数
//系数为0不进行输出
//如果size为0,直接输出0
//最后没有空格
float poly[1001];

void _1002() {
stack<float> coefficients;
stack<int> exponents;
//每行几个多项式
int n, exp;
float cof;
//共两行
for (int i = 0; i < 2; ++i) {
(void)scanf("%d", &n);
for (int i = 0; i < n; ++i) {
(void)scanf("%d%f", &exp, &cof);
poly[exp] += cof;
}
}

//次数从高到底
for (int i = 0; i <= 1000; i++) {
if (poly[i] != 0) {
coefficients.push(poly[i]);
exponents.push(i);
}
}

int count = coefficients.size();
printf("%d", count);
for (int i = 0; i < count; i++) {
float coe = coefficients.top();
int exp = exponents.top();
coefficients.pop();
exponents.pop();
printf(" %d %.1f", exp, coe);
}
}

----\(˙<>˙)/----赞赏一下吧~