一元多项式的乘法与加法运算

2023-05-06 16:44:25 浏览数 (1)

一看时限200ms用java可能过不了,但是我试了一下,用数组的话java可以过,用数组比较方便,下标就是指数,该下标的数组存放的是这个式子的系数

代码语言:javascript复制
import java.io.BufferedInputStream;
import java.util.Scanner;

public class Main {
    public static int[] a = new int[2002]; // 存放第一个多项式
    public static int[] b = new int[2002]; // 存放第二个多项式
    public static int[] c = new int[2002]; // 存放乘法
    public static int[] d = new int[2002]; // 存放加法

    public static void main(String[] args) {
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        int n1 = cin.nextInt();
        int max1 = 0, max2 = 0;
        for (int i = 0; i < n1;   i) {
            int t1 = cin.nextInt();
            int t2 = cin.nextInt();
            a[t2]  = t1;
            if (t2 > max1)
                max1 = t2; // max1记录式子1的最高指数
        }
        int n2 = cin.nextInt();
        for (int i = 0; i < n2;   i) {
            int t1 = cin.nextInt();
            int t2 = cin.nextInt();
            b[t2]  = t1;
            if (t2 > max2)
                max2 = t2; // max2记录式子2的最高指数
        }
        cin.close();
        for (int i = 0; i <= max1;   i) {
            if (a[i] != 0) {
                for (int j = 0; j <= max2;   j) {
                    if (b[j] != 0) { // 下标为指数,存放的是系数
                        c[i   j]  = a[i] * b[j]; // 系数相乘,指数相加
                    }
                }
            }
        }
        boolean flag = true;
        for (int i = max1   max2; i >= 0; --i) {
            if (c[i] != 0) {
                if (flag) {
                    System.out.print(c[i]   " "   i);
                    flag = false;
                } else {
                    System.out.print(" "   c[i]   " "   i);
                }
            }
        }
        if (flag) {
            System.out.print("0 0");
        }
        System.out.println();
        for (int i = 0; i <= max1;   i) {
            if (a[i] != 0) {
                d[i]  = a[i]; // 把式子1收进数组d
            }
        }
        for (int i = 0; i <= max2;   i) {
            if (b[i] != 0) {
                d[i]  = b[i]; // 指数相同系数相加
            }
        }
        // out
        int m = max1 > max2 ? max1 : max2; // 只需要知道最高次方即可
        boolean f = true;
        for (int i = m; i >= 0; --i) {
            if (d[i] != 0) {
                if (i == m) {
                    System.out.print(d[i]   " "   i);
                    f = false;
                } else {
                    System.out.print(" "   d[i]   " "   i);
                }
            }
        }
        if (f) {
            System.out.println("0 0");
        } else {
            System.out.println();
        }
    }
}

0 人点赞