This time, you are supposed to find A+B where A and B are two polynomials.
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, Ni and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK<⋯<N2<N1≤1000.
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.
这道题的题意就是多项式相加,
特别注意 当两个多项式相加系数为0时就不用输出
此题的思路
第一种方法:
用map key装次数,value装系数,有相同的key 就直接相加,当value为0就直接移除
第二种方法:https://www.jianshu.com/p/52e39671574c
可以不用map设定一个一维数组进行遍历,数组的下标为次方,数组中的内容为值
最后的格式要正确 多输了一个空格 找了一个h 细心!
这道题
1.学习了TreeMap 中
能够把它保存的记录根据key排序,默认是按升序排序,也可以指定排序的比较器2.LinkMap顺序输出
3.map中 的Map.entry 返回set集合 包含了map中的映射关系,然后运用迭代器遍历map中的元素
4.运用java中的比较器 比较集合中的元素
Comparetor接口
Comparable接口的 compareto 方法
比较只用
o1 o2
表示 o1 在 o2的前面 只用考虑大的情况 o1>o2 o1到 o2的前面(约定俗成)
import java.util.*; /** * TreeMap: 能够把它保存的记录根据key排序,默认是按升序排序,也可以指定排序的比较器 */ public class Main { private static Scanner sc = new Scanner(System.in); public static void main(String[] args){ Map<Integer,Float> map = new TreeMap<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { //使map中的元素以降序排列 return o2-o1; } }); for(int i=0;i<2;i++){ int k=sc.nextInt(); for(int j=0;j<k;j++){ int power=0; Float num; power=sc.nextInt(); num=sc.nextFloat(); if(map.containsKey(power)){ float pre = map.get(power); map.put(power,pre+num); }else{ map.put(power,num); } if(map.get(power)==0){ map.remove(power); } } } sc.close(); System.out.print(map.size()); Set<Map.Entry<Integer, Float>> set = map.entrySet(); Iterator<Map.Entry<Integer, Float>> it = set.iterator(); while(it.hasNext()){ Map.Entry<Integer,Float> entry = it.next(); // if(entry.getValue()==0) // continue; System.out.printf(" %d %.1f",entry.getKey(),entry.getValue()); } } }