原题
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:
where K is the number of nonzero terms in the polynomial, and (i = 1, 2, ⋯, K) are the exponents and coefficients, respectively. It is given that
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,其中 A 和 B 是两个多项式。
输入规范:
每个输入文件包含一个测试用例。每个案例占 2 行,每行包含一个多项式的信息:
其中 K 是多项式中非零项的数目,,(i = 1, 2, ⋯, K)分别是指数和系数。给定
输出规范:
对于每个测试用例,应在一行中输出 A 和 B 的乘积,格式与输入相同。请注意,每行末尾不得有多余的空格。请精确到小数点后 1 位。
解题思路
第一眼感觉可以暴力解,但是由于没想到系数可能是负数写了好久总是不过,后来给系数加上绝对值就ac了
代码(c++)
#include <bits/stdc++.h>
using namespace std;
const int N = 2010;
int n1, n2, x;
double a[N], b[N], m[N]; // a为第一多项式,b为第二,m为答案多项式
int main(){
cin >> n1;
for(int i = 0; i < n1; i++) cin >> x >> a[x];
cin >> n2;
for(int i = 0; i < n2; i++) cin >> x >> b[x];
for(int i = 0; i <= 1000; i++)
for(int j = 0; j <= 1000; j++)
if(fabs(a[i]) > 1e-5 && fabs(b[j]) > 1e-5) m[i + j] += a[i] * b[j]; // 此处要加fabs()因为系数可能为负数
int count = 0;
for(int i = N; i >= 0; i--)
if(fabs(m[i]) > 1e-5) count++;
printf("%d", count);
for(int i = N; i >= 0; i--)
if(fabs(m[i]) > 1e-5) printf(" %d %.1lf", i, m[i]);
}