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

多项式的和

Description

This time, you are supposed to find A+B where A and B are two polynomials.
这一次你的任务是求解A+B,这里的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 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

#include 
#include 
using namespace std;
#define MAX 1001
#define EPS 0.05

void Input();
void Clear();
void Add();
void Output();

double a[MAX],b[MAX],c[MAX];//数组a和b是分别用来记录这两组输入的多项式,c是用来记录相加的结果的
int n,k;

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

void Clear(){
    int i;
    n=0;
    for (i = 0; i < MAX; i++) {
        a[i]=0.0;
        b[i]=0.0;
        c[i]=0.0;
    }
}

void Input(){//输入这两行多项式
    int i,e;
    double temp;
    for (i = 0; i <k; i++) {
        scanf("%d",&e);
        scanf("%lf",&a[e]);
    }
    scanf("%d",&k);
    for (i = 0; i <k; i++) {
        scanf("%d",&e);
        scanf("%lf",&b[e]);
    }
}

void Add(){
    int i;
    for (i=0;i<MAX;i++){
        c[i]=a[i]+b[i];
    }
}

void Output(){
    int i;
    for (i=MAX-1;i>=0;i--){
        if(fabs(c[i])>=EPS){//这道题的重点就是不能直接判断 double类型的值 == 0 ,要设定一个精度EPS,小于这个精度EPS的值都可以认为就是0
            n++;
        }
    }

    if(0==n){
        printf("0\n");
    }else{
        printf("%d",n);
        for (i=MAX-1;i>=0;i--){
            if(fabs(c[i]>=EPS)){
                printf(" %d %.1lf",i,c[i]);
            }
        }
        printf("\n");
    }
}

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