1009. Product of Polynomials

1. 原题:https://www.patest.cn/contests/pat-a-practise/1009

2. 方法思路:

思路: 题意是求两多项式的乘积。有多种数据结构,可以用链表,
或者STL中的set,map等。然后就是逐项相乘啦。
为求算法简便,选用map。

3.源代码(已AC)

#include<iostream>
#include<map>
using namespace std;

/*
思路: 题意是求两多项式的乘积。有多种数据结构,可以用链表,
或者STL中的set,map等。然后就是逐项相乘啦。
为求算法简便,选用map。
*/
int main()
{
	//freopen("in.txt", "r", stdin);
	map<int, double> m1, m2, m3;	//定义三个容器;
	int k1, k2, i, exp;
	double coe;
	cin >> k1;	//读取数据;
	for(i = 0; i < k1; i++)
	{
		cin >> exp >> coe;
		m1[exp] = coe;	//插入容器;
	}
	cin >> k2;
	for(i = 0; i < k2; i++)
	{
		cin >> exp >> coe;
		m2[exp] = coe;
	}

	map<int, double>::iterator it1, it2;	//定义两个正向迭代器
	for(it1 = m1.begin(); it1 != m1.end(); it1++)
	{
		for(it2 = m2.begin(); it2 != m2.end(); it2++)	//逐项相乘;
		{
			exp = it1->first + it2->first;
			coe = it1->second * it2->second;
			if(m3.count(exp))	//判读含exp的项是否存在;
			{
				m3[exp] += coe;
				if(m3[exp] == 0)	//系数为0删除该项;
					m3.erase(exp);
			}
			else
				m3[exp] = coe;
		}
	}

	cout << m3.size();
	map<int, double>::reverse_iterator rit;	//定义反向迭代器,map默认是按照key升序。
	for(rit = m3.rbegin(); rit != m3.rend(); rit++)
		printf(" %d %.1lf", rit->first, rit->second);
	cout <<endl;

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值