PAT甲级-1002 A+B for Polynomials (25)(25 分)

1002 A+B for Polynomials (25)(25 分)

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

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~ ... NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.

Output

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

来源: https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000

思路:将多项式相加转化为指数相同的每一项都累加到以该指数为下标的数组元素中去,最后逆序输出累加后的多项式

//C++代码
#include <stdio.h>

//接收一行数据,将多项式每项的系数累加到以该项的指数为下标的数组ex[]中
void intput(double ex[])
{
     int k, e;
  double c;
  scanf("%d", &k);
  while (k--)
  {
   scanf("%d %lf", &e, &c);
   ex[e] += c;
  }
}

int main(void)
{
  //初始化数组为0,接收两行数据,自动对指数相同的项进行累加
 double ex[1001]={0};
 intput(ex);
 intput(ex);
	
 //数出累加后的多项式共有多少项
 int i, count=0;
 for (i = 1000; i >= 0; i--) if (ex[i] != 0) count ++;
 printf("%d", count);
	
 //输入是逆序的,题目要求输出也要逆序打印多项式的每一系数非零项
 for (i = 1000; i >= 0; i--)	if (ex[i] != 0) printf(" %d %.1f", i, ex[i]);
 return 0;
}

猜你喜欢

转载自blog.csdn.net/yeziand01/article/details/80715848