PAT甲级 1002 A+B for Polynomials(25) (模拟)

题目

This time, you are supposed to find A+B where A and B are two polynomials.

输入

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.

输出

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.

样例输入 

2 1 2.4 0 3.2
2 2 1.5 1 0.5

样例输出 

3 2 1.5 1 2.9 0 3.2

题意理解

题意很简单就是两个多项式合并,输入第一行是K 然后有N个数 分别是指数和系数,最后求出合并完的那个多项式。根据题意简单模拟一下即可,观察到这里指数只到1000,所以开个double数组存下来即可,运用了哈希映射的思想。

注意:这题的坑点就是如果前一个是负的,后一个是正的,那么我们合并完以后这一项就变成了0,那么就不需要输出了。

代码 

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int cnt=0;
int t,n,m,sum;
double ans[N];
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
    	int x;
		double nu;
    	cin>>x>>nu;
    	ans[x]+=nu;
	}
	cin>>n;
    for(int i=0;i<n;i++){
    	int x;
		double nu;
    	cin>>x>>nu;
    	ans[x]+=nu;
	}
	for(int i=0;i<1010;i++){
		if(ans[i]!=0)cnt++;
	}
	printf("%d",cnt);
	for(int i=1010;i>=0;i--){
		if(ans[i]!=0)printf(" %d %0.1lf",i,ans[i]); 
	}
	puts("");
    return 0;
}


版权声明:本文为NHS6671原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。