PAT --甲级1009(1009 Product of Polynomials )

本文详细介绍了一种解决多项式乘法问题的算法,通过结构化的节点操作实现两个多项式的相乘,输出结果遵循特定格式,保留非零项并按指数从大到小排序。文章提供了完整的代码示例,包括输入输出格式、数据结构定义和核心运算逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1009 Product of Polynomials (25 分)

This time, you are supposed to find A×BA\times BA×B where AAA and BBB 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:

KKK N1N_1N1 aN1a_{N_1}aN1 N2N_2N2 aN2a_{N_2}aN2 ... NKN_KNK aNKa_{N_K}aNK

where KKK is the number of nonzero terms in the polynomial, NiN_iNi and aNia_{N_i}aNi (i=1,2,⋯,Ki=1, 2, \cdots , Ki=1,2,,K) are the exponents and coefficients, respectively. It is given that 1≤K≤101\le K \le 101K10, 0≤NK<⋯<N2<N1≤10000 \le N_K < \cdots < N_2 < N_1 \le 10000NK<<N2<N11000.

Output Specification:

For each test case you should output the product of AAA and BBB 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.

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

给两个多项式,格式为:k(该多项式的项数) 指数 系数
求这两个多项式相乘的结果,输出项数以及各个指数从大到小的非零项。

思路:模拟,数据规模不大,用数组即可(如果数据规模大的话可能要用键值对树存储)。注意有个坑点:结果要输出非零项的项数以及非零项,项数的问题很容易忽略!然后指数它的测试数据为整数(如果为浮点数的话注意考虑精度问题)

Code

#include <bits/stdc++.h>

using namespace std;
const double esp = 1e-6;

struct Node {
	double zhishu;
	double xishu;
	
	Node operator * (const Node& A) const {
		Node tmp;
		tmp.zhishu = zhishu + A.zhishu;
		tmp.xishu = xishu * A.xishu;
		return tmp;
	}
	
	bool operator == (const Node& A) const { //指数相同
		if (fabs(zhishu - A.zhishu) <= esp) {
			return true;
		}
		return false;
	}
	
	bool operator < (const Node& A) const {
		return zhishu > A.zhishu;
	}
};

int k1,k2;
vector<Node> A, B, C;

int main() {
	Node tmp;
	A.clear(); B.clear(); C.clear();
	cin >> k1;
	for (int i = 0; i < k1; i++) {
		cin >> tmp.zhishu >> tmp.xishu;
		A.push_back(tmp);
	}
	cin >> k2;
	for (int i = 0; i < k2; i++) {
		cin >> tmp.zhishu >> tmp.xishu;
		B.push_back(tmp);
	}
	for (int i = 0; i < k1; i++) {
		for (int j = 0; j < k2; j++) {
			tmp = A[i] * B[j];
			int z = 0;
			for (; z < C.size(); z++) {
				if (tmp == C[z]) {
					break;
				}
			}
			if (z < C.size()) {
				C[z].xishu += tmp.xishu;
			} else {
				C.push_back(tmp);
			}
		}
	}
	for (vector<Node>::iterator it = C.begin(); it != C.end(); it++) {
		if (fabs(it->xishu) <= esp) {
			C.erase(it);
		}
	}
	sort(C.begin(), C.end());
	printf("%d", C.size());
	for (int i = 0; i < C.size(); i++) {
			printf(" %.0lf %.1lf", C[i].zhishu, C[i].xishu);
	}
	printf("\n");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小胡同的诗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值