PTA-1002——A+B for Polynomials

Posted orangecyh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PTA-1002——A+B for 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:

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???? (,) are the exponents and coefficients, respectively. It is given that 1,0.

Output Specification:

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.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2

题目分析:

读懂题意后很水,K表示输入几组,每组两个数构成,表示N次项的系数为aN。例如:A的2次项系数为3.0,B的2次项系数为4.1,A+B的和中2次项系数为7.1.要注意的地方是保留一位小数。

代码:

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     double x[1001]={0};
 5     int k1,k2;
 6     cin>>k1;
 7     int a;
 8     double b;
 9     while(k1--){
10         cin>>a>>b;
11         x[a]+=b;
12     }
13     cin>>k2;
14     while(k2--){
15         cin>>a>>b;
16         x[a]+=b;
17     }
18     int Count=0;
19     for(int i=0;i<=1000;i++){
20         if(x[i]!=0){
21             Count++;
22         }
23     }
24     cout<<Count;
25     for(int i=1000;i>=0;i--){
26         if(x[i]!=0){
27             cout<<" "<<i<<" ";
28             printf("%.1f",x[i]);  //保留小数点后面1位 
29         }
30     }
31     return 0; 
32 } 

 


以上是关于PTA-1002——A+B for Polynomials的主要内容,如果未能解决你的问题,请参考以下文章

[PTA] 1002. 写出这个数 (Basic)

[PTA]1002 写出这个数

SPOJ - POLYNOM Polynomial(数论乱搞)题解

为自己的数据类型定义 Ord 实例

c语言for循环输入九九乘法表

题目1001:A+B for Matrices