7-2 Multiplication and addition of unary polynomials (20 points)

The design function calculates the product and sum of two unary polynomials respectively.

Input format:

The input is divided into 2 lines, and each line first gives the number of non-zero terms of the polynomial, and then enters a polynomial non-zero term coefficient and exponent in an exponentially descending manner (the absolute value is an integer not exceeding 1000). Numbers are separated by spaces.

Output format:

The output is divided into 2 lines, and the coefficients and exponents of the product polynomial and the non-zero term of the sum polynomial are output in an exponentially descending manner, respectively. Numbers are separated by spaces, but there can be no extra spaces at the end. The zero polynomial should output 0 0.

Input sample:

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1

Sample output:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

Use arrays to represent polynomials, P1[et] = ct; et is the exponent, and ct is the coefficient.

The array S[SIZE] calculates the sum of two polynomials, the same coefficients are added, and the different coefficients are added.

The array M[SIZE*2] calculates the product of two polynomials whose coefficients are not zero, and the subscript indicates the addition of the exponents after multiplication.

#include<bits/stdc++.h>
using namespace std;
#define SIZE 2005
int main()
{
    int n,m,ct,et,P1[SIZE]={},P2[SIZE]={},S[SIZE]={},M[SIZE*2]={};
    bool flag = 0;
    scanf("%d",&n);
    for(int i = 0;i<n;i++){
        scanf("%d",&ct);
        scanf("%d",&et);
        P1[et] = ct;
    }
    scanf("%d",&m);
    for(int i = 0;i<m;i++){
        scanf("%d",&ct);
        scanf("%d",&et);
        P2[et] = ct;
    }
    for(int i = 0;i<=SIZE;i++){
        if(P1[i] != 0) S[i] += P1[i];
        if(P2[i] != 0) S[i] += P2[i];
    }
    for(int i = 0;i<=SIZE;i++){
        if(P1[i] != 0){
            for(int j = 0;j<=SIZE;j++){
                if(P2[j] != 0){
                    M[i+j] += P1[i]*P2[j];
                }
            }
        }
    }
    for(int i = SIZE;i>=0;i--){
        if(M[i] != 0){
            if(flag) printf(" ");
            flag = true;
            printf("%d %d",M[i],i);
        }
    }
    if(!flag) printf("0 0");
    printf("\n");
    flag = false;
    for(int i = SIZE;i>=0;i--){
        if(S[i] != 0){
            if(flag) printf(" ");
            flag = true;
            printf("%d %d",S[i],i);
        }
    }
    if(!flag) printf("0 0");
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_53514496/article/details/127188246