PAT 1002 A+B for Polynomials (25 分)Java实现

1. 题意

给两个多项式,把它们加起来
样例分析:
A多项式
2 1 2.4 0 3.2 第一个2指得是2个非0系数项
然后的两个数,1是项数,2.4是系数
最后两个数,0是项数,3.2是系数
所以就有f(x) = 2.4x + 3.2
B多项式
2 2 1.5 1 0.5
f(x) = 1.5x² + 0.5x
所以它们的和就是F(x) = 1.5x² + 2.9x + 3.2,然后我们先输出总项数,再依次输出这个多项式的项数和系数

2. 思路

用数组下标存项数,数组值存系数

2. 代码:

package adv1002;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main {
    static double[] a, b, sum;
    static int maxn = 1005;

    public static void main(String[] args) throws IOException {
        int count = 0;
        a = new double[maxn];
        b = new double[maxn];
        sum = new double[maxn];
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] aLine = br.readLine().split(" ");
        String[] bLine = br.readLine().split(" ");
        int K = Integer.parseInt(aLine[0]);
        int M = Integer.parseInt(bLine[0]);


        for (int i = 1, j = 1; i <= K; i++) {
            int n = Integer.parseInt(aLine[j++]);
            double p = Double.parseDouble(aLine[j++]);
            sum[n] += p;
        }

        for (int i = 1, j = 1; i <= M; i++) {
            int n = Integer.parseInt(bLine[j++]);
            double p = Double.parseDouble(bLine[j++]);
            sum[n] += p;
        }

        for (int i = 0; i < maxn; i++) {
            if (sum[i] != 0) {
                count++;
            }
        }
        System.out.print(count);
        for (int i = maxn - 1; i >= 0; i--) {
            if (sum[i] != 0) {
                System.out.print(" " + i + " " + String.format("%.1f", sum[i]));
            }
        }
    }
}

你可能感兴趣的:(pat,PAT)