算法导论-实验三-多项式的乘积

多项式的乘积

Description

This time, you are supposed to find A*B where A and B are two polynomials.
这一次你的任务是计算两个多项式A和B的乘积

Input

Each input file contains multiple 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.
每个输入文件包含多组测试数据,每组测试数据有2行,每行数据是一个多项式的信息:K N1 aN1 N2 aN2 … NK aNK,其中K是非零整数,表示多项式的项数,Ni和aNi(i=1,2,…,K))表示每一项的幂和系数,K和NK符合1 <= K <= 10,0 <= NK < … < N2 < N1 <=1000。

Output

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

#include 
#include 
#include 
#include 
using namespace std;

#define EPS 0.0499

double dA[1001],dB[1001],dC[2001],dOut[101];
int nOut[101];
int i,j;
int nCnt,nPow;
int nNzero;

void Clear();
void Input();
void Mul();
void Output();

int main(){
    while (1== scanf("%d",&nCnt)){
        Clear();
        Input();
        Mul();
        Output();
    }
    return 0;
}

void Clear(){   //注意这里可以用memset来做初始化操作
    memset(dC,0,sizeof(dC));
    memset(dB,0,sizeof(dB));
    memset(dA,0,sizeof(dA));
    memset(dOut,0,sizeof(dOut));
    memset(nOut,0,sizeof(nOut));
    nNzero=0;
}

void Input(){
    for (i=1;i<=nCnt;i++){
        scanf("%d",&nPow);
        scanf("%lf",&dA[nPow]);
    }
    scanf("%d",&nCnt);
    for (i=1;i<=nCnt;i++){
        scanf("%d",&nPow);
        scanf("%lf",&dB[nPow]);
    }
}

void Mul(){
    for (i=0;i<1001;i++){
        for (j=0;j<1001;j++){
            dC[i+j]+=dA[i]*dB[j];
        }
    }
}

void Output(){
    for(i=2000;i>=0;i--){
        if (fabs(dC[i])>=EPS){ //同样的这里double类型的变量不能直接用 == 判断是否为0,同样要设置一个EPS精度
            nNzero++;
        }
    }
    if(0==nNzero){
        printf("0\n");
    }else{
        printf("%d",nNzero);
        for (i=2000;i>=0;i--){
            if(fabs(dC[i]>=EPS)){
                printf(" %d %.1lf",i,dC[i]);
            }
        }
        printf("\n");
    }
}

你可能感兴趣的:(算法导论,c语言)