PAT甲级——A+B for Polynomials

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 N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​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

思路1:

     题目要求的是多项式的和,并输出所有系数非零的多项式数目,以及按照指数从大到小的顺序输出多项式每一项的指数和系数。首先可以考虑建立一个map映射,将多项式的指数和系数对应起来。输入第一组数据的时候可以直接建立映射,并且建立一个布尔型的hashTable[],用来记录已经出现过的指数,再输入第二组数据的时候,如果输入的指数之前已经存在了,那么就需要将指数对应的系数在原来的基础上加上后面输入的系数,如果输入的指数之前没有出现过那么就建立新的指数和系数的映射。输出数据的时候由于map会按照键的值从小到达输出,那么我们需要利用反向迭代器map<int,float>::reverse_iterator it来从后往前输出,起点为mp.rbegin()(包含),终点为mp.rend()(不包含)。

代码:

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

map<int, float>mp;
bool hashTable[1010] = { false };

int main()
{
	int n1, n2, N;
	float  a;
	scanf("%d", &n1);
	for (int i = 0; i < n1; i++)
	{
		scanf("%d %f", &N, &a);
		mp[N] = a;
		hashTable[N] = true;
	}
	scanf("%d", &n2);
	for (int i = 0; i < n2; i++)
	{
		scanf("%d %f", &N, &a);
		if (hashTable[N] == true)
			mp[N] += a;
		else
			mp[N] = a;
	}
	map<int, float>::iterator ip;
	map<int, float>::reverse_iterator it;
	int len = mp.size();

	int count = 0;
	for (ip = mp.begin(); ip != mp.end(); ip++)
	{
		if ((int)ip->second != 0)
			count++;
	}
	printf("%d", count);

	for (it = mp.rbegin(); it != mp.rend(); it++)
	{
		if ((int)it->second != 0)
            printf(" %d %.1f", it->first, it->second);
	
	}

	return 0;

}

思路2:

        设立a数组,⻓度为指数的最大值,a[i] = j表示指数i的系数为j,接收a和b输入的同时将对应指数 的系数加入到a中,累计a中所有非零系数的个数,然后从后往前输出所有系数不为0的指数和系数。

代码:
 

#include <iostream>
using namespace std;

int main()
{
	float a[1010] = { 0 };
	int m, n, t;
	float num;
	scanf_s("%d", &n);
	for (int i = 0; i < n; i++)
	{
		scanf_s("%d%f", &t, &num);
		a[t] += num;
	}
	scanf_s("%d", &m);
	for (int i = 0; i < m; i++)
	{
		scanf_s("%d%f", &t, &num);
		a[t] += num;
	}
	int count = 0;
	for (int i = 0; i < 1010; i++)
	{
		if ((int)a[i] != 0)
			count++;
	}
	printf_s("%d", count);
	for (int i = 1009; i >= 0; i--)
	{
		if ((int)a[i] != 0)
			printf_s(" %d %.1f", i, a[i]);
		
	}
	return 0;
	
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值