19

PAT_甲级_1009 Product of Polynomials

 3 years ago
source link: https://segmentfault.com/a/1190000027083130
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

题目大意:

给定2个多项式,求他们的乘积

算法思路:

直接模拟2个多项式乘积的过程即可,使用数组A和B分别存放2个多项式,其中下标为指数,其值为系数,然后使用result保存两者相乘的结果,对于A的每一项都与B的每一项相乘,然后只要该项不为0,就将结果累加到result对应的指数位置,最后统计result不为0的项个数并且输出结果即可。

注意点:

1、注意得初始化数组

2、注意空格的输出

3、result的数组大小至少为2001,因为有可能有指数为2000的项。

提交结果:

RRbAjuN.png!mobile

AC代码:

#include<cstdio>

using namespace std;

int main(){
    int K;
    int N;//指数
    double AN;//系数 
    double A[1001] = {};
    double B[1001] = {};
    double result[2001] = {};
    //先输入多项式A 
    scanf("%d",&K);
    for(int i=0;i<K;++i){
        scanf("%d %lf",&N,&AN);
        A[N] = AN;
    }
    //再输入多项式B 
    scanf("%d",&K);
    for(int i=0;i<K;++i){
        scanf("%d %lf",&N,&AN);
        B[N] = AN;
    }
    //计算A乘以B
    for(int i=0;i<1001;++i){
        for(int j=0;j<1001;++j){
            double multi = A[i]*B[j];
            if(multi!=0){
                result[i+j] += multi;
            }
        }
    } 
    // 统计result不为0的项数 
    int num = 0;
    for(int i=0;i<2001;++i){
        if(result[i]!=0){
            ++num;
        }
    }
    // 输出结果
    printf("%d",num);
    for(int i=2000;i>=0;--i){
        if(result[i]!=0){
            printf(" %d %.1lf",i,result[i]);
        }
    } 
    return 0;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK