PAT(甲级)1009 Product of Polynomials (25分)

题目来源:PAT(甲级)1009 Product of Polynomials (25分)
题目描述:
This time, you are supposed to find A×B where A and B 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: K N1 a​N​1 N​2​​ a​N​2​​ … N​K​​ a​N​K where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​ (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.

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.

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

题目大意: 多项式乘法的计算
题目思路:

  1. 利用map存储两个需要计算的多项式
  2. 通过遍历进行多项式各项的乘法运算,并存储到新的map中(为什么选择map? 因为map可以进行自动排序!!!)
  3. 按照要求输出

注意事项:

  • 第一个测试点样例中考虑到了系数为0的情况,这种情况下要将该项删除,并且各项要按照指数降序的顺序的排列,由于我用的是map就不用再进行排序的操作
  • 计算共有几项的时候要记得出去系数为0的项
  • 最后输出的时候,系数如果为整数记得保留一位小数,我用的是C语言的输出办法 printf ( “%.lf” , num )
#include<iostream>
#include<map>
using namespace std;

struct non {
	int ex;
	float co;
};

int main()
{
	int K1, K2;
	cin >> K1;	
	int ex;
	float co;
	map<int, float>re;
	map<int, float>m1;
	map<int, float>m2;
	for (int i = 0;i < K1;i++)
	{
		cin >> ex >> co;
		m1.insert(pair<int, float>(ex, co));
	}
	cin >> K2;
	for (int i = 0;i < K2;i++)
	{
		cin >> ex >> co;
		m2.insert(pair<int, float>(ex, co));
	}
	//做多项式乘法
	int num = 0;
	int temp_ex;
	float temp_co;
	map<int, float>::iterator it1, it2;
	for (it1 = m1.begin();it1 != m1.end();it1++) {
		for (it2 = m2.begin();it2 != m2.end();it2++) {
			temp_ex = it1->first + it2->first;
			temp_co = it1->second*it2->second;
			//方法一:利用迭代器进行遍历
			/*map<int, float>::iterator iter = re.find(temp_ex);
			if (iter == re.end())
			{
				re.insert(pair<int, float>(temp_ex, temp_co));
			}
			else
			{
				iter->second += temp_co;
				if (iter->second == 0.0)
					re.erase(iter->first);
			}*/
			//方法二:不使用迭代器
			if (re.find(temp_ex) == re.end())
			{
				re[temp_ex] = temp_co;
			}
			else
			{
				re[temp_ex] += temp_co;
				if (re[temp_ex] == 0.0)
					re.erase(temp_ex);
			}
		}
	}
	map<int, float>::reverse_iterator it;
	cout << re.size(); //统计大小
	for (it = re.rbegin();it != re.rend();it++)
	{
		cout << " " << it->first << " ";
		printf("%.1lf", it->second);	
	}
	cout << endl;
	return 0;
}

map的用法参考:https://blog.csdn.net/forever__1234/article/details/89647975

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值