题目描述
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 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 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 k1,k2,i,j,k,count=0;
scanf("%d",&k1);
double a[2][k1];
for(i=0;i<k1;i++){
scanf("%lf",&a[0][i]);
scanf("%lf",&a[1][i]);
}
scanf("%d",&k2);
double b[2][k2];
for(i=0;i<k2;i++){
scanf("%lf",&b[0][i]);
scanf("%lf",&b[1][i]);
}
double sum[2][k1+k2];
for(i=0,j=0,k=0;i<k1&&j<k2;k++){
if(a[0][i]>b[0][j]){
sum[0][k]=a[0][i];
sum[1][k]=a[1][i];
i++;
count++;
continue;
}
if(a[0][i]<b[0][j]){
sum[0][k]=b[0][j];
sum[1][k]=b[1][j];
j++;
count++;
continue;
}
if(a[0][i]==b[0][j]){
if(a[1][i]+b[1][j]!=0){
sum[0][k]=b[0][j];
sum[1][k]=a[1][i]+b[1][j];
i++;
j++;
count++;
}else{
i++;
j++;
}
continue;
}
}
for(k=i;k<k1;k++){
sum[0][count]=a[0][k];
sum[1][count]=a[1][k];
count++;
}
for(k=j;k<k2;k++){
sum[0][count]=b[0][k];
sum[1][count]=b[1][k];
count++;
}
printf("%d",count);
for(k=0;k<count;k++){
printf(" %.0lf %.1lf",sum[0][k],sum[1][k]);
}
}
注意空格问题
方法二
用一维数组保存,由于题目给出限制0≤NK<⋯<N2<N1≤1000,指数小于1000,因此用下标做指数,用数组数据存放系数,建立大小为1002的数组逐一扫描即可