PAT 1002 A+B for Polynomials

原题目

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 \ N_1 \ a_{N_1} \ N_2 \ a_{N_2} \ ... \ N_K \ a_{N_K}
where K is the number of nonzero terms in the polynomial, N_iand a_{N_i} (i = 1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 \leq K \leq 10, 0 \leq N_K \lt ... \lt N_2 \lt N_1 \leq 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

题目大意

求多项式A和多项式B相加的结果。
输入两行数据用来表示两个多项式。每行数据格式如下:

K \ N_1 \ a_{N_1} \ N_2 \ a_{N_2} \ ... \ N_K \ a_{N_K}

其中K指该多项式所含非零系数项的个数,N_ia_{N_i}分别指某一项的指数和系数,且满足K在1到10之间,N_i按降序排列。
要求按照输入的格式输出这两个多项式的和,且系数的值需保留一位小数。注意输出时行尾不能出现多余的空格。

题解

一开始用Python做,有几个测试用例死活过不了。参考了几篇文章过后还是换成了C语言来写。具体思路为以输入的指数为下标将系数存储在数组里,最后遍历数组输出非零的结果即可。
注意题目中要求的输出格式,相加后系数为0的多项式不能出现在输出里。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
    double exp[1001];
    int k, n;
    double a;
    int cnt = 0;
    memset(exp, 0, sizeof(exp));
    for(int m=0;m < 2;m++){
        scanf("%d", &k);
        for(int i=0;i < k;i++){
            scanf("%d %lf", &n, &a);
            if(exp[n] == 0){
                cnt++;
            }
            exp[n] += a;
            if(exp[n] == 0){
                cnt--;
            }
        }
    }
    printf("%d", cnt);
    for(int i=1000;i >=0;i--){
        if(exp[i] != 0)
            printf(" %d %.1lf", i, exp[i]);
    }
    printf("\n");
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容