多项式运算,注意为0情况

This time, you are supposed to find A×B where A and B are two polynomials.

Input Specification:

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 … N**K aNK

where K is the number of nonzero terms in the polynomial, N**i and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 0≤N**K<⋯<N2<N1≤1000.

Output Specification:

For each test case you should output the product 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 up to 1 decimal place.

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 3 3.6 2 6.0 1 1.6

实现思想

一个数组记录第一组数据

一个数组用来放结果,注意大小为2001

接收第二组数据,一边输入一边计算,将结果放到数组中

根据数组元素不为0输出系数和指数

代码实现

#include <iostream>
#include <vector>
#include <cstdio>

using namespace std;
vector<double> polynomials(1001);
vector<double> result(2001, 0.0);
int main() {
    int n, m, exponents, num=0;
    double coefficients;
    cin >> n;
    for(int i = 0; i < n; i++) {
        scanf("%d %lf", &exponents, &coefficients);
        polynomials[exponents] = coefficients;
    }
    cin >> m;
    for(int j = 0; j < m; j++) {
        scanf("%d %lf", &exponents, &coefficients);
        for(int k = 0; k < 1001; k++) {
            result[exponents + k] += coefficients * polynomials[k];
        }
    }
    for(int h = 0; h < 2001; h++){
        if(result[h] != 0.0)
            num++;
    }
    cout << num;
    for(int t = 2000; t >= 0; t--){
        if(result[t] != 0.0) {
            printf(" %d %.1f", t, result[t]);
        }
    }
    return 0;
}