✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1002 A+B for Polynomials (pintia.cn)
🔑中文翻译:多项式 A + B
📣专栏定位:为想考甲级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 N 1 a N 1 N 2 a N 2 . . . N K a N K K\ N_1\ a_{N_1}\ N_2\ a_{N_2}\ ...\ N_K\ a_{N_K} K N1 aN1 N2 aN2 ... NK aNK
where K is the number of nonzero terms in the polynomial, N i N_i Ni and a N i a_{N_i} aNi ( i = 1 , 2 , ⋯ , K ) (i=1,2,⋯,K) (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1 ≤ K ≤ 10 , 0 ≤ N K < ⋯ < N 2 < N 1 ≤ 1000 1≤K≤10,0≤N_K<⋯<N_2<N_1≤1000 1≤K≤10,0≤NK<⋯<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:
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
和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;
}