PAT A1002 A+B for Polynomials (25分)

PAT A1002 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:K N1​​ a​N​1​​​​ N​2​​ a​N​2​​ ... N​K​​ a​N​Kwhere K is the number of nonzero terms in the polynomial, N​i​ and aN​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 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

大体题意

A和B都是多项式,其中k表示项数,Ni表示指数,Ani表示系数,因此要将A和B相加,就是将有相同指数的项的系数相加。
注意若相加后系数为0,则不该显示此项了
还需注意最后输出的时候,指数的项先输出

思路

设置数组mp记录指数为n项的系数为mp[n]
此外设置set容器,用来存储系数不为0的项的指数
当输入A的多项式时,mp[n]+=a,然后判断若a==0则从set temp中删除,如果a!=0则添加入set。使用这个数组和set容器后,输入B的多项式也可以用同样操作
使用set的目的是即使添加入多次重复的数字,set具有去重功能,避免了麻烦
最后要求指数大的先输出,用两种方法,一种遍历set再保存在栈中,一种直接反向遍历set
set的具体使用在PAT基础知识
测试点问题,该题目要求保留一位小数,如果测试点1不通过很有可能是这个问题
这里就用到了
cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(1) << x;
头文件
#include <iomanip>

代码

#include <iostream>
using namespace std;
#include <set>
#include <stack>
#include <iomanip>

set<int> temp;
float mp[10001] = { 0 };

int main()
{
	int ka, kb;
	cin >> ka;
	int n;
	float a;
	for (int i = 0; i < ka; i++)
	{
		cin >> n >> a;
		mp[n] += a;
		if (mp[n] == 0)
		{
			temp.erase(n);
		}
		else
		{
			temp.insert(n);
		}
	}
	cin >> kb;
	for (int i = 0; i < kb; i++)
	{
		cin >> n >> a;
		mp[n] += a;
		if (mp[n] == 0)
		{
			temp.erase(n);
		}
		else
		{
			temp.insert(n);
		}
	}
	stack<int> s;
	if (temp.size() != 0)
	{
		cout << temp.size();
		for (auto it = temp.begin(); it != temp.end(); it++)
			s.push(*it);
		while (!s.empty())
		{
			int d = s.top();
			s.pop();
			cout << " " << d << " " << setiosflags(ios::fixed | ios::showpoint) << setprecision(1) << mp[d];
		}
	}
	else
		cout << "0" << endl;
	return 0;
}

运行结果

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值