1009 Product of Polynomials

This time, you are supposed to find A×B where A and B are two polynomials.

这次,你需要找到两个多项式 AB 的乘积。

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

K\quad N_1\quad a_{N1}\quad N_2\quad a_{N2}\quad...\quad N_K\quad a_{NK}

where K is the number of nonzero terms in the polynomial, N_i and a_{Ni} (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$.

每个输入文件包含一个测试用例。每个用例占据 2 行,每行包含一个多项式的信息:

K\quad N_1\quad a_{N1}\quad N_2\quad a_{N2}\quad...\quad N_K\quad a_{NK}

其中 K 是多项式中非零项的数量,N_ia_{Ni}i=1,2,⋯,K)分别是指数和系数。给定$1≤K≤10, 0≤N_K<⋯<N_2<N_1≤1000$。

Output Specification:

For each test case you should output the product 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 up to 1 decimal place.

对于每个测试用例,你应该在一行中输出 AB 的乘积,格式与输入相同。请注意,每行末尾不能有额外的空格。请精确到小数点后 1 位。

Sample Input:

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:

3 3 3.6 2 6.0 1 1.6

样例说明

直接上样例:

2 1 2.4 0 3.2

表示多项式a含有2个非零项$2.4x^1+3.2x^0$

同理

2 2 1.5 1 0.5

表示多项式b含有2个非零项$1.5x^2+0.5x^1$

a\times b的结果(2.4x^1+3.2x^0)\times(1.5x^2+0.5x^1)=3.6x^3+2.6x^2+1.6x^1

3 3 3.6 2 6.0 1 1.6

即有3个非零项$3.6x^3+2.6x^2+1.6x^1$

我的思路

这是一个数学、模拟题。思路很简单。

#include<bits/stdc++.h>
using namespace std;
int main(){
	int K1,K2;
	cin>>K1;
	double a[K1][2];
	for(int i=0;i<K1;i++){
		cin>>a[i][0]>>a[i][1];
	}
	cin>>K2;
	double b[K2][2];
	for(int i=0;i<K2;i++){
		cin>>b[i][0]>>b[i][1];
	}
	double res[2001]={0};
	for(int i=0;i<K1;i++){
		for(int j=0;j<K2;j++){
			int n=a[i][0]+b[j][0];
			res[n]+=a[i][1]*b[j][1];
		}
	}
	int count=0;
	for(int i=0;i<2001;i++){
		if(res[i]){
			count++;
		}
	}
	cout<<count;
	for(int i=2000;i>=0;i--){
		if(res[i]!=0.0){
			printf(" %d %.1f",i,res[i]);
		}
	}
}

晚上11点,6000+提交,真是奇观!

image.png

Solution

#include <iostream>
using namespace std;
int main() {
    int n1, n2, a, cnt = 0;
    scanf("%d", &n1);
    double b, arr[1001] = {0.0}, ans[2001] = {0.0};
    for(int i = 0; i < n1; i++) {
        scanf("%d %lf", &a, &b);
        arr[a] = b;
    }
    scanf("%d", &n2);
    for(int i = 0; i < n2; i++) {
        scanf("%d %lf", &a, &b);
        for(int j = 0; j < 1001; j++)
                ans[j + a] += arr[j] * b;
    }
    for(int i = 2000; i >= 0; i--)
        if(ans[i] != 0.0) cnt++;
    printf("%d", cnt);
    for(int i = 2000; i >= 0; i--)
        if(ans[i] != 0.0)
            printf(" %d %.1f", i, ans[i]);
    return 0;
}

标题:PAT 1009 多项式乘法
作者:Departure
地址:https://www.unreachablecity.club/articles/2023/04/26/1682522184358.html