PAT甲级 1002 A+B for Polynomials (25分)

1002 A+B for 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:
​​ 在这里插入图片描述
where K is the number of nonzero terms in the polynomial, Ni (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that :
在这里插入图片描述

Output Specification:
For each test case you should output the sum 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 to 1 decimal place.

Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output:
3 2 1.5 1 2.9 0 3.2

输入有2行,每行按照(多项式非零项数个数 指数1 系数1 指数2 系数2 ……)的格式输入。
即要我们算2个多项式的和,再按相同的格式输出就好了。
其中注意删除系数为零的项,②以及输出时按照题中要求(Please be accurate to 1 decimal place.)保留一位小数即可。

C++实现

#include
#include
using namespace std;
int main()
{
	int count=2;
	map<int,double,greater<int> > mp;
	while(count--)
	{
		int m;
		cin>>m;
		while(m--)
		{
			int a;
			double b;
			cin>>a>>b;
			mp[a]+=b;
		}
	}
	for(auto it=mp.begin();it!=mp.end();)//遍历一遍map,删除系数为零的项。 
	{
		if(it->second==0) mp.erase(it++);
		else it++; 
	}
	cout<<mp.size();//输出项数个数 
	for(auto it=mp.begin();it!=mp.end();it++)//按指数(exponents) 系数(coefficients)的格式输出
	{
		printf(" %d %.1f",it->first,it->second);//根据题目要求,系数保留1位小数。 
	}
	return 0;
}

你可能感兴趣的:(PAT甲级 1002 A+B for Polynomials (25分))