1. 程式人生 > >【PAT甲級】1002 A+B for Polynomials

【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​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N​K​​<⋯<N​2​​<N​1​​≤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

個人思路

這題就是求多項式的和,兩種思路,一種是用兩個陣列存,然後最後逐個比較最後輸出,還有一種就是用一個大小為1000的double陣列儲存指數為i,係數為poly[i]的項,在輸入的時候就合併到其中。最後從大到小輸出即可。我實現的是第二種思路。

有一個小坑,就是題目要求精確到1位小數,已在題目中加粗。

程式碼實現

#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iostream>
#define ll long long
#define ep 1e-5
#define INF 0x7FFFFFFF

const int maxn = 1005;

using namespace std;

int main() {
    double poly[maxn];
    memset(poly, 0, sizeof(poly));
    int k1, k2, k = 0;
    // 輸入第一個多項式
    cin >> k1;
    for (int i = 0; i < k1; i ++) {
        int idx;
        cin >> idx;
        cin >> poly[idx];
    }
    // 在輸入第二個多項式的同時合併
    cin >> k2;
    for (int i = 0; i < k2; i ++) {
        int idx;
        double tmp;
        cin >> idx >> tmp;
        poly[idx] += tmp;
    }
    // 統計多項式和的項數
    int max = 0;
    for (int i = 0; i < maxn; i ++) {
        if (poly[i] != 0) {
            k ++;
            max = i;
        }
    }
    // 輸出
    cout << k;
    for (int i = max; i >= 0; i --) {
        if (poly[i] != 0) {
            printf(" %d %.1lf",i, poly[i]);        }
    }
    return 0;
}

總結

學習不息,繼續加油