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 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.
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 Input2 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
题目大意:每组输入有两行,每行第一个数字表示多项式的个数,接着先输入一项的指数然后输入对应的系数,
要求输出两行的多项式相加的结果,以同样的格式输出,指数大小一次递减;
思路:指数的范围是0~1000,可以定义一个数组,数组小标表示指数,数组元素表示系数;两者之和系数相加,
例题是这样的 2.4*x^1 +3.2*x^0 和 1.5*x^2+0.5*x^1 相加就是 1.5*x^2 + 1.2*x^1 + 3.2*x^0
第一次提交wa 问题在于,如果多项式相加后为0 那么只输出0然后换行,而不是输出0 0 0;
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
double ans[1001];
int n,k;
double N;
for(int i=0 ;i<1001 ;i++){
ans[i]=0;
}
cin>>n;
while(n--){
cin>>k>>N;
ans[k] += N;
}
cin>>n;
while(n--){
cin>>k>>N;
ans[k] += N;
}
int flag = 1;
int count = 0;
for(int i=1000 ;i>=0 ;i--){
if(ans[i]!=0){
count ++;
}
}
printf("%d",count);//注意这里 如果输出0 这样的话后面就没空格
for(int i=1000 ;i>=0 ;i--){
if(ans[i]!=0){
printf(" %d %.1f",i,ans[i]);
}
}
printf("\n");
return 0;
}