输入为两行,分别表示两个多项式。表示每项的整数对按照次数大小降序给出。(次数绝对值小于1000,系数绝对值小于10000)
按照降次顺序输出表示和多项式的整数对(系数为0的整数对不用输出,整数对由空格分隔,最后一个整数对后不添加空格)
3 3 5 -2 1 4 0 4 2 3 -1 2 1 1 3 0
3 5 2 3 -1 2 -1 1 7 0
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { Map<Integer, Integer> firstMap = new HashMap<Integer, Integer>(); Map<Integer, Integer> secondMap = new HashMap<Integer, Integer>(); int n = scanner.nextInt(); for(int i = 0; i < n; i++) { int xiShu = scanner.nextInt(); int zhiShu = scanner.nextInt(); firstMap.put(zhiShu,xiShu); } int m = scanner.nextInt(); for (int i = 0; i < m; i++) { int xiShu = scanner.nextInt(); int zhiShu = scanner.nextInt(); secondMap.put(zhiShu,xiShu); } for(Map.Entry<Integer, Integer> entry : secondMap.entrySet()) { if (firstMap.containsKey(entry.getKey())) { int xiShuResult = firstMap.get(entry.getKey())+entry.getValue(); if (xiShuResult == 0) { firstMap.remove(entry.getKey()); }else { firstMap.put(entry.getKey(), xiShuResult); } }else { firstMap.put(entry.getKey(), entry.getValue()); } } List<Map.Entry<Integer, Integer>> myList = new ArrayList<>(firstMap.entrySet()); //按照Map的key进行排序 myList.sort(Map.Entry.comparingByKey()); for (int i = myList.size()-1; i >= 0; i--) { System.out.print(myList.get(i).getValue()+ " " + myList.get(i).getKey()+" "); } } } }
import java.util.Scanner; public class Main { public static void main(String[] args) { int []a=new int[10001]; Scanner sc=new Scanner(System.in); int n1=sc.nextInt(); for(int i=0;i<n1;i++) { int xishu=sc.nextInt(); int zhishu=sc.nextInt(); a[zhishu+1000]+=xishu;//指数可能有负数的情况 } int n2=sc.nextInt(); for(int i=0;i<n2;i++) { int xishu=sc.nextInt(); int zhishu=sc.nextInt(); a[zhishu+1000]+=xishu; } StringBuilder sb=new StringBuilder(); for(int i=a.length-1;i>=0;i--) {//10000 if(a[i]!=0) sb.append(a[i]+" "+(i-1000)+" "); } System.out.println(sb.toString().trim()); } }