PAT-A1002 A+B for Polynomials (25分)

原题

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​N​1​​ N​2 aN ​2 ​​ … N​K a ​NK

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

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

Sample Output:

3 2 1.5 1 2.9 0 3.2

分类

数组映射(map或自定义哈希数组)

题意说明

计算两个多项式的和

思路分析

  1. 计算多项式之和时,将相同次数项的系数相加即可
  2. 题目给出两个多项式,每个输入的第一个数字k表示非零系数项个数,之后是k对指数和系数。要求结果精确到小数点后1位。
  3. 几个注意点:
  • 同次数项的系数互为相反数时,最后结果不输出该项
  • 相同系数相加后结果为0,则输出结果为“0”(后面不再有任何输出)

参考代码

方法一:用map存储各项系数,并用cnt记录结果中的非零项

#include <cstdio>
#include <map>
using namespace std;
map <int, double> res;
int main(){
    int k, ex;
    double co;
    scanf("%d", &k);
    //cnt 记录结果中非零项个数
    int cnt = 0;
    for (int i = 0; i < k ; ++i) {
        scanf("%d%lf", &ex, &co);
        res[ex] = co;
        cnt++;
    }
    scanf("%d", &k);
    for (int i = 0; i < k ; ++i) {
        scanf("%d%lf", &ex, &co);
        //第一个多项式中无对应次数项,则结果中的非零项自增1
        if(res[ex] == 0) cnt++;
        res[ex] += co;
        //两非零项相加结果为0,则结果中的非零项自减1
        if(res[ex] == 0) cnt--;
    }
    printf("%d", cnt);
    if(cnt == 0){
        return 0 ;
    }
    auto it = res.end();
    while(it != res.begin()){
        it--;
        if(it->second!=0){
            printf(" %d %.1lf", it->first, it->second);
        }
    }
    return 0;
}

方法二:同样用map存储系数,但不用cnt记录结果中非零系数

#include <cstdio>
#include <map>

using namespace std;
map<int, double> res;

int main() {
    int k, ex;
    double co;
    scanf("%d", &k);
    for (int i = 0; i < k; ++i) {
        scanf("%d%lf", &ex, &co);
        res[ex] = co;
    }
    scanf("%d", &k);
    for (int i = 0; i < k; ++i) {
        scanf("%d%lf", &ex, &co);
        res[ex] += co;
        //相加结果为0时直接移除对应项
        if (res[ex] == 0) res.erase(ex);
    }
    printf("%d", res.size());
    if (res.size() == 0) {
        return 0;
    }
    auto it = res.end();
    while (it != res.begin()) {
        it--;
        if (it->second != 0) {
            printf(" %d %.1lf", it->first, it->second);
        }
    }
    return 0;
}

方法三:也可以用哈希数组存储各项系数,方法类似,在此不赘述。

发布了5 篇原创文章 · 获赞 0 · 访问量 760

猜你喜欢

转载自blog.csdn.net/qq_36382924/article/details/104068194