PAT甲级(Advanced Level) Practice 1009 Product of Polynomials

本文介绍了解决一个编程问题,计算两个多项式的乘积,特别注意处理可能出现的负数系数,并确保输出结果精确到小数点后一位。解题者分享了暴力解法并给出了C++代码示例,强调了在计算过程中对绝对值的使用以适应负数系数的情况。
摘要由CSDN通过智能技术生成

原题

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\leq K\leq 10, 0\leq N_{K}< ...< N_{2}<N_{1}\leq 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

题目翻译 

这次,你要找出 A×B,其中 A 和 B 是两个多项式。

输入规范:

每个输入文件包含一个测试用例。每个案例占 2 行,每行包含一个多项式的信息: K N_{1}a_{N_{1}} N_{2}a_{N_{2}}...N_{K}a_{N_{K}}

其中 K 是多项式中非零项的数目,N_{i}a_{N_{i}}(i = 1, 2, ⋯, K)分别是指数和系数。给定1\leq K\leq 10, 0\leq N_{K}< ...< N_{2}<N_{1}\leq 1000 

输出规范:

对于每个测试用例,应在一行中输出 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]);
}


 

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值