【PAT】A1009 Product of Polynomials (25point(s))


Author: CHEN, Yue
Organization: 浙江大学
Time Limit: 400 ms
Memory Limit: 64 MB
Code Size Limit: 16 KB

A1009 Product of Polynomials (25point(s))

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

Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int maxn = 1010;
int main(){
	double data1[maxn], data2[maxn], data3[2 * maxn];	// 乘积的长度最多翻倍(19、20 408)
	int k, exponent, count = 0;
	double coefficient;
	memset(data1, 0, sizeof(data1));	// data[i]存x^i前的系数
	memset(data2, 0, sizeof(data2));
	memset(data3, 0, sizeof(data3));
	scanf("%d", &k);		// 处理第一个多项式的数据
	for (int i = 0; i < k; i++){
		scanf("%d %lf", &exponent, &coefficient);
		data1[exponent] = coefficient;
	}
	scanf("%d", &k);		// 处理第二个多项式的数据
	for (int i = 0; i < k; i++){
		scanf("%d %lf", &exponent, &coefficient);
		data2[exponent] = coefficient;
	}
	for (int i = 0; i < maxn; i++){	// 对应项相乘,存储结果
		for (int j = 0; j < maxn; j++)
			data3[i + j] += data1[i] * data2[j];	// 次数相加,系数相乘
	}
	for (int i = 2 * maxn - 1; i >= 0; i--) {	// 计算非零项个数
		if (data3[i] != 0.0)
			count++;
	}
	printf("%d", count);
	for (int i = 2 * maxn - 1; i >= 0; i--) {
		if (data3[i])
			printf(" %d %.1f", i, data3[i]);
	}
	printf("\n");
	return 0;
}

Analysis

-已知两个多项式的非零项个数k。依次给出k组数据(形式:次数 该次数前系数)。

-求两个多项式的乘积。输出格式与输入格式相同。

-分别处理第一个多项式和第二个多项式。按照指数相加,系数相乘,将结果存入结果数组。并计算非零项个数。注意系数需要保留一位小数。

扫描二维码关注公众号,回复: 8815564 查看本文章
发布了159 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ztmajor/article/details/103776829