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:

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 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 } 

猜你喜欢

转载自www.cnblogs.com/orangecyh/p/10268257.html