1002 A+B for Polynomials

1.题目

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 K N_1 a_{N_1} N_2 a_{N_2} ... N_K a_{N_K} KN1aN1N2aN2...NKaNK
where K K Kis the number of nonzero terms in the polynomial, N i N_i Ni and a N i a_{N_i} aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤ N K N_K NK<⋯< N 2 N_2 N2< N 1 N_1 N1≤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.

2.输入输出样例

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

3.题目分析

Polynomial是多项式的意思,A和B是两个多项式,用两行输入,将AB相加得到新的多项式,在一行中输出。

K是多项式的项数,即该多项式一共有多少项,N是第几项,a是第N项具体数值。

要做的是将对应项相加,并最终输出。

4.具体代码

#include
using namespace std;
int main() {
    double N[1001] = {0}, m;
    int k, max = 0, tmp, count=0;    //max为多项式的最大指数
    for (int i = 0; i < 2; i++) {
        cin >> k;
        for (int j = 0; j < k; j++) {
            cin >> tmp >> m;
            max = tmp > max ? tmp : max;
            N[tmp] += m;
        }
    }
    for (int i = 0; i <= max; i++) {
        if (N[i] != 0)
            count++;
    }
    cout << count;
    if (count > 0) {
        for (int i = max; i >=0; i--) {
            if (N[i] != 0) 
                printf(" %d %0.1lf",i, N[i]);           
        }
    }
    return 0;
}

你可能感兴趣的:(PAT甲级)