1002 A+B for Polynomials (多项式相加)

    xiaoxiao2025-03-04  38

    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:

    K N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

    where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N​K​​<⋯<N​2​​<N​1​​≤1000.

    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 输入 1 1 0 2 1 1 2 1 输出 2 2 1.0 1 1.0 //这组输出中系数为0 不能输出 输入 2 1 2.4 0 3.2 2 2 1.5 1 0.5 输出 3 2 1.5 1 2.9 0 3.2 输入 3 1 0 3 1 0 -3 1 1 2 输出 3 3 1.0 1 2.0 0 -3.0 //在这组输出中发现多打了空格

    这道题的题意就是多项式相加,

    特别注意 当两个多项式相加系数为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()); } } }

     

    最新回复(0)