PAT 甲级 1002题

题目:1002 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 N1​ aN1​​ N2​ aN2​​ ... NK​ aNK​​

where K is the number of nonzero terms in the polynomial, Ni​ and aNi​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK​<⋯<N2​<N1​≤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

解题思路:

可以设置一个数组,下标为指数,存储的数据是系数,然后通过输入依次将值按照指数(下标)存入数组中,再遍历数组,输出值不为0的项。

注意:

①测试点1:当输出的时候需要将系数保留1位小数;

②测试点3/4/5/6:当A、B对应指数的系数相加正好为0的时候,其输出项数需要仔细的计算(即为当系数为0的时候,需要将该项去掉);

代码:

cpp 复制代码
#include<iostream>
using namespace std;
#define MAX 1002
int main()
{
	float arr[MAX] = {0.0f};    //对应指数作为数组下标,其存储的内容为该指数对应的系数
	int zhishu = 0;   //指数
	float xishu = 0;    //系数
	int K = 0;   //表示未知数的个数
	int K_Sum = 0;   //表示最终表达式的未知数个数

	//输入
	int j = 2;
	while(j--)   //输入两轮:A和B
	{
		cin>>K;
		K_Sum += K;
		while(K--)
		{
			cin>>zhishu>>xishu;
			for(int i=0;;i++)
			{
				if(i == zhishu)
				{
					if(arr[i] != 0.0f)   //如果A和B有相同的指数
					{
						K_Sum--;
						arr[i] += xishu;
						if(arr[i] == 0.0f)    //系数相加结果为0
						{
							K_Sum--;
						}
						break;
					}
					arr[i] += xishu;
					break;
				}
			}
		}
	}

	//输出
	cout<<K_Sum;
	for(int i=1001;i>=0;i--)
	{
		if(arr[i] != 0.0f)
		{
			cout<<" "<<i<<" ";
			printf("%.1f",arr[i]);
		}
	}
	cout<<endl;
	system("pause");
	return 0;
}
相关推荐
小O的算法实验室15 小时前
2026年SEVC SCI2区,基于k均值聚类和自适应双群策略的粒子群算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
李日灐15 小时前
C++STL: list(双链表) 简单介绍,了解迭代器类型,list sort 的弊端
开发语言·c++·list
脏脏a15 小时前
栈 & 队列:面试题(括号 / 循环队列)+ 概念题,全考点覆盖
数据结构·栈和队列面试题
打不了嗝 ᥬ᭄15 小时前
【Linux】多路转接 Select , Poll和Epoll
linux·网络·c++·网络协议·http
程序员-King.15 小时前
day115—同向双指针—将x减到0的最小操作数(LeetCode-1658)
算法·leetcode·双指针
全栈工程师修炼指南15 小时前
Nginx | 负载均衡策略:一致性哈希算法实践
运维·算法·nginx·负载均衡·哈希算法
Jerryhut15 小时前
sklearn函数总结六——特征降维 压缩数据 - 特征提取(PCA&LDA)
人工智能·算法·机器学习·scikit-learn·sklearn
啊森要自信15 小时前
【C++的奇迹之旅】map与set应用
c语言·开发语言·c++
apcipot_rain15 小时前
CCF算法能力大赛T3 暴力法 反思
算法
pu_taoc15 小时前
ffmpeg实战4-将PCM与YUV封装成MP4
c++·ffmpeg·pcm