PTA 一元多项式的乘法与加法运算

一开始用c语言写特别麻烦,最近学了c++,c++写这题挺简单的

题目如下:

 它要求我们降序输出,且多项式相乘相加无重复项,我们可以用map来写这道题

//用map容器来写这道题,map能自动排序
#include<iostream>
#include<map>
using namespace std;
class comPare {//一个降序的仿函数
public:
	bool operator()(int v1, int v2) const{
		return v1 >  v2;
	}
};
int main() {
	map<int, int,comPare>m1,m2,result;
	map<int, int,comPare>::iterator it1, it2;
	int n;
	cin >> n;
	while (n--) {
		int x1, x2;
		cin >> x1 >> x2;
		m1[x2] = x1;	//注意题目中指数在第二个,我们得把它放在key值
	}
	cin >> n;
	while (n--) {
		int x1, x2;
		cin >> x1 >> x2;
		m2[x2] = x1;
	}
	for (it1 = m1.begin(); it1 != m1.end(); it1++) {	//用一个多项式的每一项去乘另外一个多项式,结果放到第三个map中
		for(it2 = m2.begin(); it2 != m2.end(); it2++) {
			int re1, re2;
			re1 = (it1->first) + (it2->first), re2 = (it1->second) * (it2->second);
			if (result.find(re1) == result.end()) {//没找到直接添加
				result[re1] = re2;
			}
			else if (result[re1] + re2 != 0) {
				result[re1] += re2;
			}
			else {
				result.erase(re1);//为0就直接删除这一项
			}
		}
	}
	if (result.size() == 0) {//零多项式按要求输出
		cout << "0 0" << endl;
	}
	else {
		int i = 0;
		for (map<int, int, comPare>::iterator it = result.begin(); it != result.end(); it++, i++) {
			if (i > 0) cout << " ";
			cout << it->second << " " << it->first;
		}
		cout << endl;
	}
	for (it2 = m2.begin(); it2 != m2.end(); it2++) {
	if (m1.find(it2->first) == m1.end()) {
		m1.insert(pair<int, int>(it2->first, it2->second));
	}
	else {
		int re2,re1;
		re1 = it2->first;
		re2 = m1[re1] + (it2->second);
		if (re2 == 0) {
			m1.erase(re1);//为0删除
		}else{
		m1[re1]=re2;
		}
	}
	 }
	if (m1.size() == 0) {
		cout << "0 0" << endl;
	}
	else {
		int i = 0;
		for (map<int, int, comPare>::iterator it3 = m1.begin(); it3 != m1.end(); it3++, i++) {
			if (i > 0) cout << " ";
			cout << it3->second << " " << it3->first;
		}
		cout << endl;
	}
	return 0;
	}

提交结果: 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值