【一只蒟蒻的刷题历程】 【PAT (Advanced Level) Practice】 1002 多项式的A + B

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


题目大意:

这次,您应该找到A + B,其中A和B是两个多项式。

输入规格:

每个输入文件包含一个测试用例。 每个案例占用2行,并且每行包含一个多项式的信息:

K N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ … N​K​​ a​N​K​​​​

其中K是多项式中非零项的数量,N i和a N i(i = 1,2,⋯,K)分别是指数和系数。 假设1≤K≤10,0≤Nk <= … <= N1≤1000。

输出规格:

对于每个测试用例,应在一行中输出A和B的总和,格式与输入相同。 请注意,每行末尾不得有多余的空间。 请精确到小数点后一位。

样本输入:

2 1 2.4 0 3.2 (2.4x1 + 3.2x0
2 2 1.5 1 0.5   (1.5x2 + 0.5x1)

样本输出:

3 2 1.5 1 2.9 0 3.2  (1.5x2 + 2.9x1 + 3.2x0)

注意:

1:每行末尾不得有多余的空间。
2:请精确到小数点后一位。(没仔细看这个,一直错。。。)

代码:

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
using namespace std;
int main() 
{
    int k,n; //非零项数量 , 指数 
    double an; //系数 
    map<int,double> ans;
     //直接开个double数组也行,map<指数,系数>
        
    cin>>k;
	for(int i=0;i<k;i++) 
	{
		cin>>n>>an;
		ans[n] += an; //累加该指数的系数
	} 
	
	cin>>k;
	for(int i=0;i<k;i++)
	{
		cin>>n>>an;
		ans[n] += an; //累加该指数的系数
	} 
    
    int size=0;
	for(int i=0;i<=1000;i++) //不为0,size才++
	 if(ans[i]) size++;
	
	cout<<size;
	for(int i=1000;i>=0;i--)
	 if(ans[i]) printf(" %d %.1f",i,ans[i]); 
	 //按格式输出
    return 0;
}

原创文章 31 获赞 35 访问量 1423

猜你喜欢

转载自blog.csdn.net/weixin_45260385/article/details/105888170