# 7-2 一元多项式的乘法与加法运算 (20 分)

7-2 一元多项式的乘法与加法运算 (20 分)

设计函数分别求两个一元多项式的乘积与和。

输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0

输入样例:

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1

输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

思路:使用map函数,map[指数] = 系数,不同的多项式相乘后指数相加,故x4和x2,x3和x3相乘后都是x6,所以map[指数]要+=,而不是=

代码如下

#include<bits/stdc++.h>

using namespace std;

int main()
{
	map<int, int> a, b, ans1, ans2;
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int x, y;
		cin >> x >> y;
		a[y] = x;
	}
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int x, y;
		cin >> x >> y;
		b[y] = x;
	}
	for (auto i = a.begin(); i != a.end(); i++)
	{
		for (auto j = b.begin(); j != b.end(); j++)
		{
			ans1[i->first + j->first] += i->second * j->second;
		}
	}
	for (auto i = a.begin(); i != a.end(); i++)
	{
		ans2[i->first] += i->second;
	}
	for (auto j = b.begin(); j != b.end(); j++)
	{
		ans2[j->first] += j->second;
	}
	for (auto i = ans1.begin(); i != ans1.end(); i++)
	{
		if (i->second == 0)
			ans1.erase(i);
	}
	for (auto j = ans2.begin(); j != ans2.end(); j++)
	{
		if (j->second == 0)
			ans2.erase(j);
	}
	if (ans1.size() == 0)
		cout << "0 0" << endl;
	else
	{
		auto i = ans1.end();
		i--;
		int  flag = 0;
		for (i; i != ans1.begin(); i--)
		{
			if (flag == 1)
			{
				cout << " " << i->second << " " << i->first;
			}
			else
			{
				cout << i->second << " " << i->first;
				flag = 1;
			}
		}
		if (flag == 1)
		{
			cout << " " << i->second << " " << i->first;
		}
		else
		{
			cout << i->second << " " << i->first;
		}
		cout << endl;
	}
	if (ans2.size() == 0)
		cout << "0 0" << endl;
	else
	{
		auto i = ans2.end();
		i--;
		int  flag = 0;
		for (i; i != ans2.begin(); i--)
		{
			if (flag == 1)
			{
				cout << " " << i->second << " " << i->first;
			}
			else
			{
				cout << i->second << " " << i->first;
				flag = 1;
			}
		}
		if (flag == 1)
		{
			cout << " " << i->second << " " << i->first;
		}
		else
		{
			cout << i->second << " " << i->first;
		}
		cout << endl;
	}
	return 0;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值