PAT练习题 1002 A+B for Polynomials
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, Niand 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
题意
- 输入两个多项式进行加法
- K是一个多项式中非零项的个数,范围:0~10
- Ni是指数,aNi是系数,指数范围:0~1000
- 注意输入和输出的时候,指数都是递减的,小数精确到一位即可
思路分析
- 每一个变量的输入都需要写一句scanf有点多余,使用双重循环输入变量(此处使用数组),在第二层循环里进行运算。
- 使用数组时根据指数进行存储,即指数为索引
- 输入格式是按照指数递减输入的,输出格式也是按照指数递减输出就行
代码实现
#include <stdio.h>
int main(void){
int n,i,sum=0,k,count=0;
double s,a[1001]={0};
//n为多项式中非零项的个数,即题目中的K
//k为指数,即题目中的Ni
//s为系数,即题目中的aNi
//sum为进行加运算后的数据在数组中存放的位置
//count为加运算后多项式中非零项的个数
for (int j=0;j<2;j++){//j<2代表输入两行
scanf("%d",&n);
for (i=1;i<=n;i++){//输入非0多项式
scanf("%d%lf",&k,&s);
if (a[k]==0) count++;
a[k]+=s;
if (a[k]==0) count--;
if (k>sum) sum=k;
}
}
//如果指数相同(即k相同),则在a[k]处进行运算并存储
//在此处对输入的格式进行修正,并进行存储
printf("%d",count);
while (sum>=0){
if (a[sum]!=0){
printf(" %d %.1f",sum,a[sum]);
}
sum--;
}
//因为输入的格式是按照指数从大到小的顺序,所以输出的时候可以使用sum指数--输出
}