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

注意注意:输出的 每行的 最后的数字 后面也不许加空格(不然会格式错误)

代码:

#include<iostream>
#include<map>
using namespace std;
map<int,int>a,b,c;
int main(){
	int n; cin>>n;
	for(int i=0;i<n;i++){
		int x,y; scanf("%d%d",&x,&y);
		a[y]=x;
	}
	c=a;
	int m; cin>>m;
	for(int i=0;i<m;i++){
		int x,y; scanf("%d%d",&x,&y);
		c[y]+=x;
		for(auto it=a.begin();it!=a.end();it++)
		   b[it->first+y]+=it->second*x;    
	}
	//printf("%d ",b.size());
	int flag=0;
	for(auto it=b.rbegin();it!=b.rend();it++){
		if(it->second){
			if(flag==0) printf("%d %d",it->second,it->first),flag=1;
			else printf(" %d %d",it->second,it->first);
		}
	}
	if(!flag) printf("0 0");
	printf("\n");
	flag=0;
	for(auto it=c.rbegin();it!=c.rend();it++){
		if(it->second){
			if(flag==0) printf("%d %d",it->second,it->first),flag=1;
			else printf(" %d %d",it->second,it->first);
		}
	}
	if(!flag) printf("0 0");
	return 0;
}

### 关于一元多项式乘法加法运算 #### 一元多项式表示 为了方便处理一元多项式乘法加法操作,通常采用链表或映射(`map`)来存储多项式的各项。对于给定的两个多项式,可以通过定义三个`map`对象分别保存第一个多项式、第二个多项式及其相乘后的结果[^2]。 #### 实现细节 ##### 数据输入读取 程序启动时需按照指定格式接收用户输入的数据,具体来说是两行字符串形式的一元多项式表达,其中包含了非零项的数量以及各非零项对应的系数和指数信息[^3]。 ##### 加法规则应用 当执行加法时,遍历两个多项式的每一项并依据相同指数下系数求和的原则更新最终的结果多项式;若遇到新出现的不同指数,则直接将其加入到结果集中去[^1]。 ##### 乘法规律遵循 针对乘法而言,通过迭代访问每一个参计算的单项式组合,并利用指数相加而系数相乘的方式构建新的项。值得注意的是,在此过程中可能会产生具有相同指数的新项,此时应当累加以确保不会存在重复键值对的存在。 ```cpp #include <iostream> #include <map> using namespace std; void addPolynomials(map<int, int>& result, const map<int, int>& poly){ for (auto& p : poly) { auto it = result.find(p.first); if(it != end(result)){ (*it).second += p.second; if ((*it).second == 0) result.erase(it); // Remove zero terms. }else{ result[p.first] = p.second; } } } int main(){ map<int,int> mp1,mp2,result_addition,result_multiplication; // Read input and fill maps... // Perform addition operation between two polynomials. addPolynomials(result_addition, mp1); addPolynomials(result_addition, mp2); // Multiplying each term of first polynomial with all terms from second one. for(auto &p1:mp1){ for(auto &p2:mp2){ int exp=p1.first+p2.first; int coef=p1.second*p2.second; auto it=result_multiplication.find(exp); if(it!=end(result_multiplication)) (*it).second+=coef; else result_multiplication[exp]=coef; if((*it).second==0)// Check after adding to remove zeros again. result_multiplication.erase(it); } } // Output results... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值