前言
提出java的解法不只是为了解题,同时也是熟悉java的一系列特性(jdk8)和java的数据结构。
题目
1002 A+B for Polynomials (25)(25 分)
This time, you are supposed to find A+B where A and B are two polynomials.
InputEach 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~ … NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (i=1, 2, …, K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000.
Output
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
中文翻译
把两个多项式按指数位系数相加,同时,如果系数和为0的不输出,小数精确到一位。
思路
多项式相加,那么肯定是以指数去寻找系数来相加
代码
import java.text.DecimalFormat;
import java.util.*;
public class Main {
public static void main(String[] argc) {
Scanner scanner=new Scanner(System.in);
Map<Integer,Double> map=new TreeMap<>((o1,o2)->o2.compareTo(o1));
//java8特性 lambda表达式,同时treeMap里面是红黑树可以有序放置参数
int size,index;
for(int i=0;i<2;i++) {
size = scanner.nextInt();
for(int j=0;j<size;j++) {
index=scanner.nextInt();
map.put(index,map.getOrDefault(index,0.0)+scanner.nextDouble());
//java8特性 getOrDefault(),如果找不到可以直接给默认值
}
}
StringBuilder stringBuilder=new StringBuilder();
//少用string直接拼接,耗内存 用stringBuilder比较好
DecimalFormat df = new DecimalFormat("0.0");
//用于格式化小数
size=0;
for(Map.Entry<Integer,Double> entry:map.entrySet()) {
if(entry.getValue()==0.0) {
continue;
}
stringBuilder.append(" "+entry.getKey()+" "+df.format(entry.getValue()));
size++;
}
stringBuilder.insert(0,size);
System.out.println(stringBuilder.toString());
}
}