【PAT甲级 - C++题解】1009 Product of Polynomials

简介: 【PAT甲级 - C++题解】1009 Product of Polynomials

1009 Product of Polynomials


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


Input Specification:


2.png

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
• 1
• 2

Sample Output:

3 3 3.6 2 6.0 1 1.6


题意


输入两行多项式,每行的第一个数表示该多项式非零项的个数,其中每一项由指数和系数构成。


要求我们将给定的两个多项式相乘,然后输出相乘后的多项式。注意,多项式相乘是要将两个多项式的每一项分别相乘。


输出格式核输入多项式的格式相似,先输出相乘后的多项式非零项的个数,然后输出每一项,但是这里是按照指数的最高项往最低项进行输出。

思路


  1. 分别输入两个多项式,用数组 ab 存储,数组中存储的是系数,指数用下标表示。
  2. 将两个多项式的每一项都相乘,存到数组 c 当中。
  3. 计算 c 中非零项的个数 k
  4. 输出结果,注意要从指数最大的非零项开始输出。


代码

#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
double a[N], b[N], c[N * 2];
void input(double x[])
{
    int k, n;
    double v;
    cin >> k;
    while (k--)
    {
        cin >> n >> v;
        x[n] = v;
    }
}
int main()
{
    input(a);
    input(b);
    //计算两多项式相乘的结果
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            c[i + j] += a[i] * b[j];
    int k = 0;    //计算多项式中非零项的个数
    for (int i = 0; i < N * 2; i++)
        if (c[i])
            k++;
    cout << k;
    for (int i = N * 2 - 1; i >= 0; i--)  //从指数最大的开始输出
        if (c[i])
            printf(" %d %.1f", i, c[i]);
    return 0;
}



目录
相关文章
|
C++
【PAT甲级 - C++题解】1040 Longest Symmetric String
【PAT甲级 - C++题解】1040 Longest Symmetric String
61 0
|
算法 C++
【PAT甲级 - C++题解】1044 Shopping in Mars
【PAT甲级 - C++题解】1044 Shopping in Mars
77 0
|
C++
【PAT甲级 - C++题解】1117 Eddington Number
【PAT甲级 - C++题解】1117 Eddington Number
71 0
|
存储 C++ 容器
【PAT甲级 - C++题解】1057 Stack
【PAT甲级 - C++题解】1057 Stack
69 0
|
存储 C++
【PAT甲级 - C++题解】1055 The World‘s Richest
【PAT甲级 - C++题解】1055 The World‘s Richest
75 0
|
C++
【PAT甲级 - C++题解】1051 Pop Sequence
【PAT甲级 - C++题解】1051 Pop Sequence
75 0
|
2天前
|
安全 编译器 程序员
【C++篇】C++类与对象深度解析(六):全面剖析拷贝省略、RVO、NRVO优化策略
【C++篇】C++类与对象深度解析(六):全面剖析拷贝省略、RVO、NRVO优化策略
13 2
|
2天前
|
存储 C++
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
12 2
【C++篇】C++类和对象实践篇——从零带你实现日期类的超详细指南
|
2天前
|
存储 编译器 C语言
C++类与对象深度解析(一):从抽象到实践的全面入门指南
C++类与对象深度解析(一):从抽象到实践的全面入门指南
19 8
|
2天前
|
C++
【C++】实现日期类相关接口(三)
【C++】实现日期类相关接口