1009. Product of 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 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and 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 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
题目大意:
给出两个多项式A和B,给出A*B的结果
解题思路:
本题的关键之处在于如何存储多项式的结果。
看了其他人的代码分享,都是用数组的方式存储的,下标存指数信息,值存系数。
多项式相乘时,相同指数的项要进行合并,比如2.4*a^2 和1.2*a^2 合并为 3.6*a^2。则原本 ans[2] = 2.4 更新为ans[2] += 1.2
最后遍历一遍整个ans数组,如果a[i] = 0.0,多项式不存在a^i这一项,否则计数器加一。要注意的是ans空间要开足够,要大于最高指数值,题目中为2000
我选择了用map存储结果,结果跳进了一个大坑,下面讲解一下用map存储需要考虑的情况
map的键值key存储指数,value存储系数
每计算出一个新的结果时,首先查看map中是否已有该键值(可以设一个mark数组进行标记,也可以直接count()>0,不过count比mark记录更耗时一些)。
如果已有该键值,更新value,并检查新的value是否不等于0.0,如果为0.0则删除该键值,mark为false。
如果没有,则插入新的键值对。
总结:
如果做题时间紧张,保证程序的鲁棒性,在时间和内存的允许下,还是优先考虑使用数组吧,比较稳妥一些。
/*
PAT 1009
2 1 2.4 0 3.2
2 2 1.5 0 0.5
1 <= K <= 10, 0 <= NK < ... < N2 < N1 <=1000.
*/
#include <cstdio>
#include <map>
#include <cstring>
using namespace std;
int fabs(int i){return i > 0 ? i : -i;}
int main(){
    int k1,k2;
    int ex[20];
    double co[20];
    map<int,double> poly;
    bool mark[2002];
    memset(mark,0,sizeof(mark));
    scanf("%d",&k1);
    for(int i = 0;i < k1;i++){
        scanf("%d %lf",&ex[i],&co[i]);
    }
    scanf("%d",&k2);
    for(int i = k1;i < k1 + k2;i++){
        scanf("%d %lf",&ex[i],&co[i]);
    }
    for(int i = 0;i < k1;i++)
    for(int j = k1;j < k1+k2;j++){
        double cot = co[i] * co[j];
        int ext = ex[i] + ex[j];
        if(mark[ext] == true){
            poly.at(ext) += cot;
            if(fabs(poly.at(ext)) < 1e-6){
                poly.erase(ext);
                mark[ext] = false;
            }
        }else{
            poly.insert(pair<int,float>(ext,cot));
            mark[ext] = true;
        }
    }
    printf("%d",poly.size());
    for(map<int,double>::reverse_iterator it = poly.rbegin();it != poly.rend();it++){
        printf(" %d %.1f",it->first,it->second);
    }
}




原文地址:https://www.cnblogs.com/starryxsky/p/7099775.html