package com.promise.pat; import java.util.*; public class P1002_2 { public static void main(String[]args){ // 使用Map // Key : 指数 // value: 系数 Scanner input = new Scanner(System.in); String line1 = input.nextLine(); String line2 = input.nextLine(); int n1 = Integer.parseInt(line1.split(" ")[0]); int n2 = Integer.parseInt(line2.split(" ")[0]); HashMap<Integer,Double> ploy1 = getData(line1,n1); HashMap<Integer,Double> ploy2 = getData(line2,n2); for (Map.Entry<Integer, Double> entry : ploy2.entrySet()) { Integer e = entry.getKey(); Double c = entry.getValue(); // ploy1中有 ploy2的key if(ploy1.containsKey(e)){ Double res = c.doubleValue() + ploy1.get(e).doubleValue(); if(res.doubleValue() == 0){ ploy1.remove(e); } else{ ploy1.put(e,res); } } // ploy1中 没有 ploy2的key else { ploy1.put(e,c); } } int size = ploy1.size(); if(size == 0){ System.out.print(size); } else{ System.out.print(size+" "); } //将keySet放入list ArrayList<Integer> list= new ArrayList<>(ploy1.keySet()); //调用sort方法并重写比较器进行升/降序 Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1<o2?1:-1; } }); Iterator<Integer> iterator = list.iterator(); //迭代排序后的key的list int count = 0; while ((iterator.hasNext())){ Integer key = iterator.next(); Double value = ploy1.get(key); System.out.print(key.intValue()+" "+ value.doubleValue()); count++; if(count != size){ System.out.print(" "); } } } public static HashMap<Integer,Double> getData(String line, int len){ HashMap<Integer,Double> map = new HashMap<>(); String[] line1Date = line.split(" "); for(int i=1;i<line1Date.length-1;i+=2){ Integer e = new Integer(line1Date[i]); Double c = new Double(line1Date[i+1]); if(c == 0){ continue; } map.put(e,c); } return map; } }