PAT甲级1002A+B for Polynomials

题目地址:

编程题 - PAT (Advanced Level) Practice (pintia.cn)

介绍

多项式加法

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.

代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long  
#define ull unsigned long long

void solve() {
	double num1[1001];
	bool num2[1001];
	memset(num1,0,sizeof(num1));
	memset(num2,0,sizeof(num2));
	int i,j,n;
	double m;
	cin>>i;
	for(j=1;j<=i;j++)
	{
		cin>>n;
		cin>>m;
		num2[n]=1;
		num1[n]+=m;
	}
	cin>>i;
	for(j=1;j<=i;j++)
	{
		cin>>n;
		cin>>m;
		num2[n]=1;
		num1[n]+=m;
	}
	n=0;
	for(i=0;i<=1000;i++)
	{
		if(num2[i]==1&&num1[i]!=0.0)
		{
			n+=1;
		}
	}
	cout<<n;
	
	for(j=1000;j>=0;j--)
	{
		if(num2[j]&&num1[j]!=0.0)
		{
			cout<<" "<<j;
			printf(" %.1f",num1[j]);
		}
	}
} 

signed main() {

    ll t = 1; 
    // std::cin >> t;
    while (t--) {
        solve();
    }
}

猜你喜欢

转载自blog.csdn.net/song0789/article/details/142502919