1002 A+B for Polynomials (25分) [多项式相加]
题目
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:
K N1 a N1 N2 a N2 … N K a NK
where K is the number of nonzero terms in the polynomial, N i and a Ni (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N K<⋯<N2<N1≤1000.
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
题目大意
输入占据两行,每行的第一个输入数字代表多项式有几项,之后分别输入系数和指数;要求计算两项多项式相加的结果。
题目分析
设置两类数组,一类数组用于存储系数,另一类用于存储指数;之后对两项多项式的每一项进行匹配,如果相等就相加;不相等则直接将该项置于和的数组里。
代码
#include "stdio.h"
int main(){
int a[25],a1[25],a2[25];//存储指数
double b[25],b1[25],b2[25];//存储系数
int i,j;
for (i=0;i<25;i++)
{
a1[i] = -10;
a2[i] = -10;
} //将指数全部赋值为-10
int sum,all;
int k1,k2;
int x;
double y;
int p = 0,q = 0;
scanf("%d",&k1);//输入第一行多项式的项数
for (i = 0;i < k1;i++){
scanf("%d%lf",&x,&y);
a1[i]=x;
b1[i]=y;
}
scanf("%d",&k2);//输入第二行多项式的项数
for (j = 0;j < k2;j++){
scanf("%d%lf",&x,&y);
a2[j]=x;
b2[j]=y;
}
sum =0;
all =0;
while (p<i||q<j){//循环条件为如果两项多项式都遍历结束,则计算结束跳出循环
if (a1[p] > a2[q]) {//如果第一项指数大于第二项,直接将第一项放入结果
a[sum]=a1[p];
b[sum]=b1[p];
p++;
sum++;
continue;
}
if (a1[p] == a2[q]) {//如果相等,两项相加;相加等于零式特判,两项多项式都往下读
a[sum]=a1[p];
b[sum]=b1[p]+b2[q];
if (b[sum]==0)
sum--;
p++;
q++;
sum++;
continue;
}
if (a1[p] < a2[q]) {//如果第一项指数大于第二项,直接将第二项放入结果
a[sum]=a2[q];
b[sum]=b2[q];
q++;
sum++;
continue;
}
}
printf("%d",sum);
for (i =0;i<sum;i++){
if (b[i] == 0)
{
continue;
}
else printf(" ");
if (i != sum-1)
printf("%d %.1lf",a[i],b[i]);
else printf("%d %.1lf",a[i],b[i]);//输出结果
}
printf("\n");
return 0;
}