1. 程式人生 > >PTA-1002——A+B for Polynomials

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 }