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
思路:
输入一个数字,表示多项式的个数,然后输入指数(e)和系数(c),将他们保存在一个数组中,用下标来表示指数(e)
这个就表示的是: 2.4x+3.2
采用这种方式将输入的值存到数组中,题目要求从按照指数从大到小输出,那就将数组倒序输出,判断a[e]为0,则不输出,仅仅输出那些非0的printf("%d%.1lf",i,a[i]);
AC代码:
#include <stdio.h>
int main(){
int N,M,count=0,e,t=10;
double c;
double a[1111]={0},b[1111]={0},res[1111]={0};
scanf("%d",&N);
for(int i=0;i<N;i++){
scanf("%d %lf",&e,&c);
a[e]=c;//下标即指数
}
scanf("%d",&M);
for(int i=0;i<M;i++){
scanf("%d %lf",&e,&c);
b[e]=c;
}
for(int i=0;i<1111;i++){//将两个多项式,按照下标对应相加,(即按照指数对应相加)
res[i]=a[i]+b[i];
if(res[i]!=0) count++;//统计多项式系数非0个数
}
printf("%d",count);//输出多项式系数非0个数
for(int i=1110;i>=0;i--){
if(res[i]!=0){//只输出非0
printf(" %d %.1f",i,res[i]);
}
}
return 0;
}
summary:
其实也可以只用一个数组存放:
for(int i=0;i<N;i++){
scanf("%d %lf",&e,&c);
a[e]+=c;//把下标(指数)相同的存在一个数组进行累加就可以了
}