PAT甲级1009 Product of Polynomials

O(n2) 暴力模拟。两个多项式相乘,也就 1e6,可以水过。

当然,也可以选择写个链表,麻烦了些。

#include 
using namespace std;
const int maxn = 1e3+1;
const int maxm = 2e3+2;
const double EPS = 1e-6;
int k;
double t[maxn];
double ans[maxm];

int main() {
    int n;
    double a;

    scanf("%d", &k);
    for (int i = 0; i < k; ++i) {
        scanf("%d%lf", &n, &a);
        t[n] = a;
    }
    scanf("%d", &k);
    for (int i = 0; i < k; ++i) {
        scanf("%d%lf", &n, &a);
        for (int j = 0; j < maxn; ++j) {
            ans[j+n] += t[j]*a;
        }
    }

    int cnt = 0;
    for (int i = 0; i < maxm; ++i) {
        if (ans[i] > EPS || ans[i] < -EPS) {
            ++cnt;
        }
    }
    printf("%d", cnt);
    for (int i = maxm-1; i >= 0; --i) {
        if (ans[i] > EPS || ans[i] < -EPS) {
            printf(" %d %.1f", i, ans[i]);
        }
    }
    return 0;
}

 

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