PAT-Java-1002-A+B for Polynomials (25)

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));
    }

  }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值