PAT笔记-A+B for polynomials

问题链接
A+B for Polynomials

问题描述

给出两组多项式A和B的系数和指数,求出多项式A和B的和C的系数和指数。

样例输入

2 1 2.4 0 3.2
2 2 1.5 1 0.5

样例输出

3 2 1.5 1 2.9 0 3.2

样例分析

对于2 1 2.4 0 3.2,得到一个有两项,第一项系数是1,指数是2.4;第二项系数是0,指数是3.2,表示为:\(A=1·x^{2.4}+0·x^{3.2}\),同理\(B=2·x^{1.5}+x^{0.5}\),得出和为\(C=2·x^{1.5}+1·x^{2.9} + 0·x^{3.2}\),所以输出为3 2 1.5 1 2.9 0 3.2(一是注意系数降序排列,二是注意即使是0也要保存系数)

算法思想

用map保存各个项,其中键是指数,值是系数;注意输出时指数倒序,所以逆向输出map;不输出系数为0的项,用空间换时间,这里定义一个vector和结构体,将答案存在其中,再输出;输出时系数保留一位小数。

实验心得

这道题的坑点在于:

  • 输出保留一位小数
  • 不输出系数为0的项

完整代码

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

//用结构体存储答案
struct Ans {
	//存储指数 
	int exp;
	//存储系数 
	double coe;
}; 
int main()
{
	//设置映射表 
	map<int,double>m;
	vector<Ans>v;
	//分别存储多项式项数 
	int a,b;
	//输入多项式A
	cin>>a;
	while(a--) {
		int n;
		double an;
		cin >> n >> an;
		m[n] += an;
	}
	//输入多项式B
	cin>>b;
	while(b--) {
		int n;
		double bn;
		cin >> n >> bn;
		m[n] += bn;
	}
	//逆向保存 
	for(map<int,double>::reverse_iterator iter = m.rbegin(); iter != m.rend(); iter++)
	{
		//注意系数为0的情况
		if(iter -> second) {
			Ans ans;
			ans.coe = iter->second;
			ans.exp = iter->first;
			v.push_back(ans);		
		}
	}
	//输出规模
	cout << v.size();
	//遍历输出(坑的是保留一位小数) 
	for (int i = 0; i < v.size(); i++) {
		printf(" %d %.1f", v[i].exp, v[i].coe);
	} 
	 
}
posted @ 2022-02-21 22:06  Carol-gutianle  阅读(40)  评论(0)    收藏  举报