PAT 1009 Product of Polynomials

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 ​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
 
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
 
 

思路#

这道题是一个多项式的乘法,考察map的使用和如何定义按照指定规则排序的map,
利用map进行遍历即可,也可以使用数组的方法,注意系数为0的情况要被删除!

**这题坑在测试点1,有系数为0的项。就是多项式的每一项乘另外多项式的每一项然后相加,然后合并同类项之后为0 !!!
 
复制代码
 1 #include <iostream>
 2 #include <stdio.h> 
 3 #include <map>
 4 #include <algorithm>
 5 #include <iterator>
 6 
 7 
 8 using namespace std;
 9 
10 double a[30];
11 double b[30];
12 map<int, double, greater<int> > mp;
13 
14 int main()
15 {
16     int ka, kb;
17     cin >> ka;
18     ka = 2*ka;
19     for(int i = 1; i <= ka; i++)
20     {
21         cin >> a[i];
22     }
23     
24     cin >> kb;
25     kb = 2*kb;
26     for(int i = 1; i <= kb; i++)
27     {
28         cin >> b[i];
29     }
30     
31         
32     for(int i = 1; i <= ka; i+=2)
33     {
34         for(int j = 1; j <= kb; j+=2)
35         {
36             mp[a[i]+b[j]] += a[i+1]*b[j+1];
37             if(mp[a[i]+b[j]] == 0)    // 合并后系数有可能为0,此时要删去
38                 mp.erase(a[i]+b[j]);
39         }
40     }
41     
42     int Size = mp.size();
43     printf("%d", Size);
44     for(auto iter = mp.begin(); iter != mp.end(); ++iter)
45     {
46         printf(" %d %.1f", iter->first, iter->second);
47     }
48 
49 
50     return 0;
51 }
复制代码

 

posted @   拾月凄辰  阅读(107)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示
主题色彩