PAT A1009. Product of Polynomials (25)

题目描述

This time, you are supposed to find A*B where A and B are two polynomials.

输入

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 (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10, 0 <= NK < … < N2 < N1 <=1000.

输出

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.

样例输入

2 1 2.4 0 3.2
2 2 1.5 1 0.5

样例输出

3 3 3.6 2 6.0 1 1.6

解题思路

用double数组表示多项式,数组下标表示幂,数组元素表示系数,注意输入空格和浮点型输出格式

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1010;
int main()
{
int K1=0;
while(cin>>K1)
{
double num[maxn]={0};
for(int i=0; i<K1; i++)
{
int NK1=0;
double aNK1=0;
cin>>NK1;
cin>>aNK1;
num[NK1]=aNK1;
}
int K2 = 0;
cin>>K2;
for(int i=0; i<K2; i++)
{
int NK2=0;
double aNK2=0;
cin>>NK2;
cin>>aNK2;
num[NK2]+=aNK2;
}
// 统计非零系数项的个数
int cnt=0;
for(int i=0; i<=1000; i++)
{
if(num[i]!=0)
{
cnt++;
}
}
cout<<cnt;
for(int i=1000; i>=0; i--)
{
if(num[i]!=0)
{
// 小数的格式化输出
printf(" %d %.1f", i, num[i]);
}
}
}
return 0;
}
分享到: