PAT A1002. A+B for Polynomials (25)

题目描述

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

输入

For each test case you should output the sum 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 to 1 decimal place.

输出

对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。

样例输入

2 1 2.4 0 3.2
2 2 1.5 1 0.5

样例输出

3 2 1.5 1 2.9 0 3.2

解题思路

用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;
}
分享到: