PTA 甲 1002 java解法

前言

提出java的解法不只是爲了解題,同時也是熟悉java的一系列特性(jdk8)和java的數據結構。

題目

1002 A+B for Polynomials (25)(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 a~N1~ N2 a~N2~ … NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (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

中文翻譯

把兩個多項式按指數位係數相加,同時,如果係數和爲0的不輸出,小數精確到一位。

思路

多項式相加,那麼肯定是以指數去尋找係數來相加

代碼

import java.text.DecimalFormat;
import java.util.*;

public class Main {
    public static void main(String[] argc) {
        Scanner scanner=new Scanner(System.in);
        Map<Integer,Double> map=new TreeMap<>((o1,o2)->o2.compareTo(o1));
        //java8特性 lambda表達式,同時treeMap裏面是紅黑樹可以有序放置參數
        int size,index;
        for(int i=0;i<2;i++) {
            size = scanner.nextInt();
            for(int j=0;j<size;j++) {
                index=scanner.nextInt();
                map.put(index,map.getOrDefault(index,0.0)+scanner.nextDouble());
                //java8特性 getOrDefault(),如果找不到可以直接給默認值
            }
        }
        StringBuilder stringBuilder=new StringBuilder();
        //少用string直接拼接,耗內存 用stringBuilder比較好
        DecimalFormat df = new DecimalFormat("0.0");
        //用於格式化小數
        size=0;
        for(Map.Entry<Integer,Double> entry:map.entrySet()) {
            if(entry.getValue()==0.0) {
                continue;
            }
            stringBuilder.append(" "+entry.getKey()+" "+df.format(entry.getValue()));
            size++;
        }
        stringBuilder.insert(0,size);
        System.out.println(stringBuilder.toString());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章