1002 A+B for Polynomials
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
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 • 1 • 2
Sample Output:
3 2 1.5 1 2.9 0 3.2
题意
输入两行多项式,每行的第一个数表示该多项式非零项的个数,其中每一项由指数和系数构成。
要求我们将给定的两个多项式相加,然后输出相加后的多项式。
输出格式核输入多项式的格式相似,先输出相加后的多项式非零项的个数,然后输出每一项,但是这里是按照指数的最高项往最低项进行输出。
思路
- 分别输入两个多项式,用数组
a
和b
存储,数组中存储的是系数,指数用下标表示。 - 将两个多项式对应的指数项的系数相加,存到数组
c
当中。 - 计算
c
中非零项的个数k
。 - 输出结果,注意要从指数最大的非零项开始输出。
代码
#include<bits/stdc++.h> using namespace std; const int N = 1010; double a[N], b[N], c[N]; int main() { int k, n; double v; cin >> k; while (k--) //输入第一组多项式 { cin >> n >> v; a[n] = v; } cin >> k; while (k--) //输入第二组多项式 { cin >> n >> v; b[n] = v; } //将两个多项式对应项相加 for (int i = 0; i < N; i++) c[i] = a[i] + b[i]; k = 0; //计算相加后多项式非零项的个数 for (int i = 0; i < N; i++) if (c[i]) k++; cout << k; for (int i = N - 1; i >= 0; i--) //从指数最大的开始输出 if (c[i]) printf(" %d %.1f", i, c[i]); return 0; }