1002 A+B for Polynomials (25 point(s))
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: … 每个输入文件包含一个测试用例。 每个案例占用2行,并且每行包含一个多项式的信息: … where K is the number of nonzero terms in the polynomial, N i N_iN … i(i=1,2,?,K) are the exponents and coefficients, respectively. It is given that …
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
Java实现 代码如下:
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;
public class ABPolynomials {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int k1 = sc.nextInt();
int [] p1_exp=new int[k1];
double [] p1_coe=new double[k1];
for(int i=0;i<k1;i++){
p1_exp[i]=sc.nextInt();
p1_coe[i]=sc.nextDouble();
}
int k2 = sc.nextInt();
int[] p2_exp = new int[k2];
double[] p2_coe = new double[k2];
for (int i =0; i<k2;i++){
p2_exp[i]=sc.nextInt();
p2_coe[i]= sc.nextDouble();
}
sc.close();
ArrayList<Integer> res_exp= new ArrayList<>();
ArrayList<Double> res_coe = new ArrayList<>();
DecimalFormat changeFormat = new DecimalFormat("0.0");
int i=k1-1,j=k2-1;
while(i>=0&&j>=0){
if(p1_exp[i]>p2_exp[j]){
res_exp.add(p2_exp[j] );
res_coe.add(p2_coe[j]);
j--;
}else if(p1_exp[i]<p2_exp[j]){
res_exp.add(p1_exp[i]);
res_coe.add(p1_coe[i]);
i--;
}else{
if((p1_coe[i]+p2_coe[j])!=0){
res_exp.add(p1_exp[i]);
res_coe.add(p1_coe[i]+p2_coe[j]);
}
i--;
j--;
}
}
while (i>=0){
res_exp.add(p1_exp[i]);
res_coe.add(p1_coe[i]);
i--;
}
while (j>=0){
res_exp.add(p2_exp[j] );
res_coe.add(p2_coe[j]);
j--;
}
int k=res_coe.size();
System.out.print(k);
for (int l = k-1; l >=0 ; l--) {
System.out.print(" "+res_exp.get(l));
System.out.print(" "+changeFormat.format(res_coe.get(l)));
}
}
}
|