PAT-甲级-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



分析:
开一个1001的数组,直接用下标代替指数,存好两行数后相加,

输出数组内非零数即可

 1 #include<stdio.h>
 2 #define N 1001
 3 
 4 int main(){
 5   float v1[N]={0},v2[N]={0},res[N]={0};
 6   int x,n;
 7   scanf("%d",&n);
 8   for(int i=0;i<n;++i){
 9       scanf("%d",&x);
10       scanf("%f",v1+x);
11   }
12   scanf("%d",&n);
13   for(int i=0;i<n;++i){
14       scanf("%d",&x);
15       scanf("%f",v2+x);
16   }
17   int cnt=0;
18   for(int i=0;i<N;++i){
19     res[i]=v1[i]+v2[i];
20     if(res[i]!=0)
21       cnt++;
22   }
23   printf("%d",cnt);
24   for(int i=N;i>0;i--)
25   {
26     if(res[i-1]!=0)
27         printf(" %d %.1f",i-1,res[i-1]);
28   }
29   return 0;
30 }
 

猜你喜欢

转载自www.cnblogs.com/tenjl-exv/p/9775874.html