✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1009 Product of Polynomials (pintia.cn)
🔑中文翻译:多项式乘积
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1009 Product of 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 product 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 up to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2 2 2 1.5 1 0.5
Sample Output:
3 3 3.6 2 6.0 1 1.6
题意
输入两行多项式,每行的第一个数表示该多项式非零项的个数,其中每一项由指数和系数构成。
要求我们将给定的两个多项式相乘,然后输出相乘后的多项式。注意,多项式相乘是要将两个多项式的每一项分别相乘。
输出格式核输入多项式的格式相似,先输出相乘后的多项式非零项的个数,然后输出每一项,但是这里是按照指数的最高项往最低项进行输出。
思路
-
分别输入两个多项式,用数组
a
和b
存储,数组中存储的是系数,指数用下标表示。 -
将两个多项式的每一项都相乘,存到数组
c
当中。 -
计算
c
中非零项的个数k
。 -
输出结果,注意要从指数最大的非零项开始输出。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
double a[N], b[N], c[N * 2];
void input(double x[])
{
int k, n;
double v;
cin >> k;
while (k--)
{
cin >> n >> v;
x[n] = v;
}
}
int main()
{
input(a);
input(b);
//计算两多项式相乘的结果
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
c[i + j] += a[i] * b[j];
int k = 0; //计算多项式中非零项的个数
for (int i = 0; i < N * 2; i++)
if (c[i])
k++;
cout << k;
for (int i = N * 2 - 1; i >= 0; i--) //从指数最大的开始输出
if (c[i])
printf(" %d %.1f", i, c[i]);
return 0;
}