1. 程式人生 > >【笨方法學PAT】1009 Product of Polynomials(25 分)

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

一、題目

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;
}