PTA (Advanced Level) 1009 Product of Polynomials
1009 Product of Polynomials
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 N1 aN1 N2 aN2 ... NK aNK
where K is the number of nonzero terms in the polynomial, Ni and aNi (,) are the exponents and coefficients, respectively. It is given that 1, 0.
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的项数K,之后跟随2K个数,即以指数 系数的方式给出A的每一项,第二行以与多项式A相同的方式给出多项式B的信息。
要求首先输出相乘后多项式的项数,之后按指数由小到大输出多项式的指数与系数
模拟运算过程,以三个double型的数组A、B、C记录给出的多项式与答案。
按要求输入多项式A,在输入多项式B时每输入一项便与A的每一项相乘,答案加入数组C中,遍历C统计非零项数量并输出,按下标由大到小输出C的非零项即可。
#include <bits/stdc++.h> using namespace std; const int MAX = 1e6+10; //指数最大为1000,多项式相乘后的最大情况无非1000*1000 double A[MAX], B[MAX], C[MAX]; //A、B为给定多项式,C记录答案 int main() { int k, max_eA = INT_MIN, max_eB = INT_MIN; scanf("%d", &k); while(k--){ //输入多项式A int en; //指数 double cn; //系数 scanf("%d%lf", &en, &cn); A[en] = cn; max_eA = max(max_eA, en); //记录多项式A的最大指数 } scanf("%d", &k); while(k--){ //输入多项式B int en; //指数 double cn; //系数 scanf("%d%lf", &en, &cn); B[en] = cn; for(int i = max_eA; i >= 0; i--) C[i + en] += A[i] * B[en];//将该多项式B的项与多项式A的所有项对应相乘 max_eB = max(max_eB, en); //记录多项式B的最大指数 } int cnt = 0; //cnt记录答案C的非零项数 for(int i = max_eA + max_eB; i >= 0; i--) if(C[i] != 0.0) cnt++; printf("%d", cnt); //输出答案项数 for(int i = max_eA + max_eB; i >= 0; i--) //输出答案多项式C if(C[i] != 0.0) printf(" %d %.1f", i, C[i]); return 0; }
若第一个测试点(测试点0)不通过,多半是double类型运算时误差的锅(输入A、B完成后再两个for循环运算就可能会出现这种问题)。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 用一种新的分类方法梳理设计模式的脉络