PAT(甲级)1002.A+B for Polynomials (25)

PAT 1002.A+B for Polynomials (25)
This time, you are supposed to find A+B where A and B are two polynomials.

输入格式:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K N1​​ a​N1 ​N​2 a​N​2... NK a​N​K​​​​
where K is the number of nonzero terms in the polynomial,N​ianda​N​i(i=1,2,⋯,K)are the exponents(指数) and coefficients(系数),respectively. It is given that 1≤K≤10,0≤N​K​​ <⋯<N2 <N1​​ ≤1000.
输出格式:
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.

输入样例:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

输出样例:

3 2 1.5 1 2.9 0 3.2

题目分析:计算两个多项表达式的和,输出格式与输入格式相同。如样例:

2 1 2.4 0 3.2  两项  y1=2.4x^1 + 3.2x^0
2 2 1.5 1 0.5  两项  y2=1.5x^2 + 0.5x^1
y3 = y1+y2  1.5x^2+2.9x^1+3.2x^0
y3有三项
输出:3   2 1.5 1 2.9 0 3.2

系数的范围:[0,1000]即1001项,可以使用数组hash,hash[exp]=coeffient, 下表exp中存储的是其对应的系数,如3.2x^100, hash[100]=3.2,所以开辟两个大小为1001的hash数组分别存储多项表达式y1和y2的系数的指数哈希数组进行预处理即可,之后分别相加系数不为0对应的hash项即可,同时统计不为0的个数。注意:输出中末行不能有空格。

AC代码:

#include <cstdio>
double a[1001], b[1001];

int main(){
    int exp, k, cnt=0;
    scanf("%d", &k);
    while(k --){
        scanf("%d", &exp);
        scanf("%lf", &a[exp]);
    }
    scanf("%d", &k);
    while(k --){
        scanf("%d", &exp);
        scanf("%lf", &b[exp]);
    }
    for(int i=0; i<=1000; ++i){
        a[i] += b[i];
        if(a[i]) cnt ++;
    }
    printf("%d",cnt);
    for(int i=1000; i>=0; --i){
        if(a[i]){
            printf(" %d %.1lf", i,a[i]);
        }
    }
    return 0;
}
发布了235 篇原创文章 · 获赞 51 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/ASJBFJSB/article/details/90347012