1. 程式人生 > >PAT--1009 Product of Polynomials (25 分)

PAT--1009 Product of Polynomials (25 分)

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​…Nk,aNk
where K is the number of nonzero terms in the polynomial, N
​i and aNi​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 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

譯文

1009 多項式乘積 (25分)
這一次,你應該找到 A × B在哪裡A和B是兩個多項式。

輸入規格:
每個輸入檔案包含一個測試用例。每個案例佔用2行,每行包含多項式的資訊:K N​1,a​N​1,N​…Nk,aNk
是指數和係數。給出了這一點1≤K≤10, 0≤NK<⋯<N2<N1<1000
輸出規格:
對於每個測試用例,您應該輸出產品 A和B在一行中,格式與輸入相同。請注意,每行末尾必須沒有額外的空間。請準確到小數點後1位。

樣本輸入:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
樣本輸出:
3 3 3.6 2 6.0 1 1.6

本想用vector陣列來做這道題,但是它處理讀入的double型別有問題,我就沒有用了。這題最難的我個人認為最難的點在於他怎麼知道它輸出是幾個數。

#include<cstdio>
#include<vector>
using namespace std;
double first[10000];
double second[10000];
double result[10000];
int main()
{
	int n;
	int max1, max2;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		int a;
		double b;
		scanf("%d%lf", &a, &b);
		if (i == 0)max1 = a;
		first[a] = b;
	}
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
	{
		int a;
		double b;
		scanf("%d%lf", &a, &b);
		if (i == 0)max2 = a;
		second[a] = b;
	}
	for (int i = 0; i <= max1; i++)
	{
		for (int j = 0; j <= max2; j++)
		{
			result[i + j] += (first[i] * second[j]);
		}
	}
	int max = max1 + max2;
	int Max = max+1;
	for (int i = max; i >= 0; i--)
	{
		if (result[i] == 0)Max--;
	}
	printf("%d", Max);
	for (int i = max; i >= 0; i--)
	{
		if (result[i] != 0)
		{
			printf(" %d %.1f", i, result[i]);
		}
	}
	return 0;
}