问题:
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:
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,
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.
问题中描述的大概意思是输入两行,每一行是一个多项式,每一行第一个数字K代表着该多项式中非零项的数量,随后是(指数 系数)。我们要做的就是将两个多项式合并,按照输入的形式输出合并后的多项式
代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] sum = new double[1001];
int count = 0;
String s1 =sc.nextLine();
String[] num = s1.split(" ");
for (int i = 1; i < num.length; i += 2) {
int exponent = Integer.valueOf(num[i]);
double coefficient = Double.parseDouble(num[i + 1]);
sum[exponent] += coefficient;
}
String s2 =sc.nextLine();
num = s2.split(" ");
for (int i = 1; i < num.length; i += 2) {
int exponent = Integer.valueOf(num[i]);
double coefficient = Double.parseDouble(num[i + 1]);
sum[exponent] += coefficient;
}
for (int i = 0; i < 1001; i++) {
if (sum[i]!=0){
count++;
}
}
System.out.print(count);
for (int i = 1000; i >= 0; i--) {
if (sum[i] != 0) {
System.out.print(" " + i);
System.out.printf(" %.1f", sum[i]);
}
}
}
}