【笨方法学PAT】1009 Product of Polynomials(25 分)

版权声明:欢迎转载,请注明来源 https://blog.csdn.net/linghugoolge/article/details/82596781

一、题目

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​​​​

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​​<⋯<N​2​​<N​1​​≤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

二、题目大意

多项式乘法

三、考点

模拟、数组

类似题目:多项式加法【笨方法学PAT】1002 A+B for Polynomials(25 分)

四、解题思路

1、使用 float 数组保存系数,指数作为数组下标;

2、读取数据,二次遍历,指数相加,系统相乘;

3、计算非0项的个数,从后向前输出非0项。

4、读取、计数和输出操作可以写在一个循环里,也可以分开。写在一起,节省运行时间;分开写的话,思路更加清晰,减少出错概率。

【注意】数组最好使用 fill 函数显式初始化,避免有未初始化的情况。

五、代码

#include<iostream>
#define N 2010
using namespace std;
int main() {
	float f1[N], f2[N], f3[N];
	fill(f1, f1 + N, 0.0);
	fill(f2, f2 + N, 0.0);
	fill(f3, f3 + N, 0.0);
	//读入数据
	int n,m;
	cin >> n;
	for (int i = 0; i < n;++i) {
		int a;
		float b;;
		cin >> a >> b;
		f1[a] = b;
	}
	cin >> m;
	for(int i=0;i<m;++i) {
		int a;
		float b;;
		cin >> a >> b;
		f2[a] = b;
	}

	//循环
	for (int i = 0; i < N/2; ++i) {
		for (int j = 0; j < N/2; ++j) {
			f3[i + j] += f1[i] * f2[j];
		}
	}

	//计算非0个数
	int ans_num = 0;
	for (int i = 0; i < N; ++i) {
		if (f3[i] != 0) {
			ans_num++;
		}
	}

	//输出
	cout << ans_num;
	for (int i = N-1; i >= 0; --i) {
		if (f3[i] != 0) {
			printf(" %d %.1f", i, f3[i]);
		}
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/linghugoolge/article/details/82596781
今日推荐