PAT1002---A+B for Polynomials

本文介绍了一种高效实现多项式求和的方法,通过定义poly结构体和使用vector容器进行操作,确保了输入多项式的正确读取和输出结果的准确性。代码示例展示了如何将两个多项式相加并保持相同的形式输出。

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

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

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.

Output

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

将两个多项式相加,想法也很简单;定义一个poly结构包含exp和coe即可,然后定义两个vector<poly>用于存储这两个加数,然后保持两个iterator使得大的放到result里面即可。注意的是当两个指数相等时应该相加,如果相加为零不应该放入结果中。代码如下:

#include<iostream>
#include<string>
#include<vector>
#include<iomanip>
using namespace std;
struct poly{
	int exp;
	double coe;
};
int main()
{
	int k1;
	cin >> k1;
	vector<poly> poly1;
	vector<poly> poly2;
	int temp_exp;
	double temp_coe;
	poly temp;
	for (int i = 0; i < k1; i++)
	{
		cin >> temp_exp >> temp_coe;
		temp.exp = temp_exp;
		temp.coe = temp_coe;
		poly1.push_back(temp);
	}
	int k2;
	cin >> k2;
	for (int i = 0; i < k2; i++)
	{
		cin >> temp_exp >> temp_coe;
		temp.exp = temp_exp;
		temp.coe = temp_coe;
		poly2.push_back(temp);
	}
	vector<poly>::iterator ptr1 = poly1.begin();
	vector<poly>::iterator ptr2 = poly2.begin();
	vector<poly> result;
	int count=0;
	while (ptr1 != poly1.end() && ptr2 != poly2.end())
	{
		if ((*ptr1).exp > (*ptr2).exp)
		{
			temp.exp = (*ptr1).exp;
			temp.coe = (*ptr1).coe;
			count++;
			++ptr1;
			result.push_back(temp);
			continue;
		}
		if ((*ptr1).exp < (*ptr2).exp)
		{
			temp.exp = (*ptr2).exp;
			temp.coe = (*ptr2).coe;
			count++;
			++ptr2;
			result.push_back(temp);
			continue;
		}
		if ((*ptr1).exp == (*ptr2).exp)
		{
			temp.exp = (*ptr1).exp;
			temp.coe = (*ptr1).coe + (*ptr2).coe;
			++ptr1;
			++ptr2;
			if (temp.coe != 0)
			{
				result.push_back(temp);
				count++;
			}
			continue;
		}
	}
	while (ptr1 != poly1.end())
	{
		result.push_back(*ptr1);
		count++;
		++ptr1;
	}
	while (ptr2 != poly2.end())
	{
		result.push_back(*ptr2);
		count++;
		++ptr2;
	}
	vector<poly>::iterator ptr = result.begin();
	cout << count;
	while (ptr != result.end())
	{
		cout << fixed << setprecision(1);
		cout << ' ' << (*ptr).exp << ' ' << (*ptr).coe;
		++ptr;
	}
	cout << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值