原题目
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:
where K is the number of nonzero terms in the polynomial, and (i = 1, 2, ..., K) are the exponents and coefficients, respectively. It is given that .
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
题目大意
求多项式A和多项式B相加的结果。
输入两行数据用来表示两个多项式。每行数据格式如下:
其中K指该多项式所含非零系数项的个数,和分别指某一项的指数和系数,且满足K在1到10之间,按降序排列。
要求按照输入的格式输出这两个多项式的和,且系数的值需保留一位小数。注意输出时行尾不能出现多余的空格。
题解
一开始用Python做,有几个测试用例死活过不了。参考了几篇文章过后还是换成了C语言来写。具体思路为以输入的指数为下标将系数存储在数组里,最后遍历数组输出非零的结果即可。
注意题目中要求的输出格式,相加后系数为0的多项式不能出现在输出里。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
double exp[1001];
int k, n;
double a;
int cnt = 0;
memset(exp, 0, sizeof(exp));
for(int m=0;m < 2;m++){
scanf("%d", &k);
for(int i=0;i < k;i++){
scanf("%d %lf", &n, &a);
if(exp[n] == 0){
cnt++;
}
exp[n] += a;
if(exp[n] == 0){
cnt--;
}
}
}
printf("%d", cnt);
for(int i=1000;i >=0;i--){
if(exp[i] != 0)
printf(" %d %.1lf", i, exp[i]);
}
printf("\n");
return 0;
}