题目描述
This time, you are supposed to find A+B where A and B are two polynomials.
输入描述:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.
输出描述:
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.
输入例子:
2 1 2.4 0 3.2 2 2 1.5 1 0.5
输出例子:
3 2 1.5 1 2.9 0 3.2
思路:
其实这一道题目主要是需要理解里面的思想,利用数组解决这个多项式的问题,题中要求的求两个多项式的和。然后输入。
首先从输入来看,这个要求输入是首先一个整数,表明第一个多项式一共有多少项,然后后面输入的是每一项的指数和系数,接着第二个多项式也是一样输入,这个时候我们要知道我们求的是两个多项式的和,那么我们能不能只用一个数组,首先用一个k保存第一个多项式的项数,然后遍历这个k然后输入第一个多项式中的每一个值,并且都保存在这个数组中,然后数组中的指数是数组的下标,而系数则是数组中的值,那么这样当我第二个多项式进行输入的时候这个时候我就可以在第一个数组的基础上相加,这样一来。
注意我们最后输入需要输出两个多项是相加后的项数和每一项的指数和系数,所以我上面在做相加的时候我就需要进行累加,而且累加的时候我只能够将这两个值相加后在进行判断。然后循环遍历这个数组。
实现:
#include<stdio.h>
const int max_n = 1111;
double a[max_n] = {};
int main(){
int k, n, count = 0;
double e;
scanf("%d", &k);
for(int i = 0; i < k; i ++){
scanf("%d%lf", &n, &e);
a[n] = e;
}
scanf("%d", &k);//这里k只是为了存储,所以这儿k是可以重复存放值。
for(int i = 0; i < k; i ++){
scanf("%d%lf", &n, &e);
a[n] += e;//这儿其实就是有相同的就相加,没有相同的就不想加
}
for(int i = 0; i < max_n; i ++){
if(a[i] != 0){
count ++;
}
}
printf("%d", count);
for(int i = max_n - 1; i >=0; i --){
if(a[i] != 0) printf(" %d %.1f", i, a[i]);
}
return 0;
}