【PAT甲级 - C++题解】1002 A+B for Polynomials

简介: 【PAT甲级 - C++题解】1002 A+B for Polynomials

1002 A+B for Polynomials

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


Input Specification:


1.png


Output Specification:

For each test case you should output the sum 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 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 2 1.5 1 2.9 0 3.2

题意


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

要求我们将给定的两个多项式相加,然后输出相加后的多项式。

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

思路


  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];
int main()
{
    int k, n;
    double v;
    cin >> k;
    while (k--)  //输入第一组多项式
    {
        cin >> n >> v;
        a[n] = v;
    }
    cin >> k;
    while (k--)  //输入第二组多项式
    {
        cin >> n >> v;
        b[n] = v;
    }
    //将两个多项式对应项相加
    for (int i = 0; i < N; i++)    c[i] = a[i] + b[i];
    k = 0;    //计算相加后多项式非零项的个数
    for (int i = 0; i < N; i++)
        if (c[i])
            k++;
    cout << k;
    for (int i = N - 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
76 0
|
算法 C++
【PAT甲级 - C++题解】1044 Shopping in Mars
【PAT甲级 - C++题解】1044 Shopping in Mars
107 0
|
C++
【PAT甲级 - C++题解】1117 Eddington Number
【PAT甲级 - C++题解】1117 Eddington Number
93 0
|
存储 C++ 容器
【PAT甲级 - C++题解】1057 Stack
【PAT甲级 - C++题解】1057 Stack
95 0
|
存储 C++
【PAT甲级 - C++题解】1055 The World‘s Richest
【PAT甲级 - C++题解】1055 The World‘s Richest
85 0
|
C++
【PAT甲级 - C++题解】1051 Pop Sequence
【PAT甲级 - C++题解】1051 Pop Sequence
90 0
|
人工智能 BI C++
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
【PAT甲级 - C++题解】1148 Werewolf - Simple Version
154 0
|
存储 定位技术 C++
【PAT甲级 - C++题解】1091 Acute Stroke
【PAT甲级 - C++题解】1091 Acute Stroke
67 0
|
2天前
|
编译器 C语言 C++
类和对象的简述(c++篇)
类和对象的简述(c++篇)
|
1月前
|
C++ 芯片
【C++面向对象——类与对象】Computer类(头歌实践教学平台习题)【合集】
声明一个简单的Computer类,含有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,以及两个公有成员函数run、stop。只能在类的内部访问。这是一种数据隐藏的机制,用于保护类的数据不被外部随意修改。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。成员可以在派生类(继承该类的子类)中访问。成员,在类的外部不能直接访问。可以在类的外部直接访问。为了完成本关任务,你需要掌握。
68 19