题目
解释
题目讲的就是给你两行,每一行第一个数字K代表多项式的非零项的数量,接着后面2K个数字,一前一后分别代表着指数和系数,让你求这两个多项式的积,输出最终多项式的非零项数量,以及按照指数从大到小的顺序,和输入一样的格式输出
解题思路
这道题和上次解决过的很像,大家可以两个一起看,1002 A+B for Polynomials(Java)
这里我定义一个TreeMap,key值存放指数,Value值存放系数,通过重写Comparator重新定义了TreeMap的排序规则
有一点需要注意的是,最后得到的结果如果系数=0,那么需要那么需要去除掉。最后系数结果保留一位小数
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s1=sc.nextLine();
String s2=sc.nextLine();
String[] arr1=s1.split(" ");
String[] arr2=s2.split(" ");
TreeMap<Integer,Double> hm=new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
for (int i = 1; i < arr1.length-1; i+=2) {
for (int j = 1; j < arr2.length-1; j+=2) {
int exponent=Integer.valueOf(arr1[i])+Integer.valueOf(arr2[j]);
double coefficient=Double.valueOf(arr1[i+1])*Double.valueOf(arr2[j+1]);
if (hm.containsKey(exponent)){
hm.put(exponent,hm.get(exponent)+coefficient);
}else{
hm.put(exponent,coefficient);
}
if (hm.get(exponent)==0){
hm.remove(exponent);
}
}
}
System.out.print(hm.size());
Set<Integer> keys = hm.keySet();
for (Integer key : keys) {
System.out.print(" "+key);
System.out.printf(" %.1f",hm.get(key));
}
}
}