1002. A+B for Polynomials (25)
题目阐述
This time, you are supposed to find A+B where A and B are two polynomials.
Input
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.
Output
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
- 原题链接
题目分析
- 原表达式如下图所示:
- 两个多项式相加,指数相同项系数相加,最后输出结果即可,思路上可以采用hash表来表达存储多项式A,键(key)使用指数(正整数Integer),值(value)使用系数(Double),然后解析多项式B的时候分别将对应系数加到多项式A的各项系数上去,这里需要注意的是浮点型数据需要保留一位小数即可,所以需要对相加后的系数进行四舍五入判别,这里的保留一位小数的技巧是很值得学习的,最后记得将键集合抽取出来排下序然后打印出来即可。代码如下:
代码如下
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;public class Main {
public static void main(String[] args) {Scanner s = new Scanner(System.in);String[] A = s.nextLine().trim().split(" ");String[] B = s.nextLine().trim().split(" ");s.close();Map<Integer, Double> map = new HashMap<>();int k1 =Integer.parseInt(A[0]); int k2 =Integer.parseInt(B[0]);for(int i=1; i<k1*2+1; i +=2)map.put(Integer.valueOf(A[i]), Double.valueOf(A[i+1]));for (int i = 1; i < k2 * 2 + 1; i += 2) {int key = Integer.valueOf(B[i]);double value = Double.valueOf(B[i + 1]);if (map.containsKey(key)) {value += map.get(key);if (Math.abs(value) <= 0.00001) {map.remove(key);} else {value = Math.round(value * 10) / 10.0;map.put(key, value);}} else {value = Math.round(value * 10) / 10.0;map.put(key, value);}}Set<Integer> set = map.keySet();List<Integer> list = new ArrayList<Integer>();for(int i : set) list.add(i);Collections.sort(list);Collections.reverse(list);System.out.print(list.size());for(int i=0; i<list.size(); i++) {int j = list.get(i);System.out.print(" " + j + " " + map.get(j));}}}