PAT甲级 1002 A+B for Polynomials

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

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~ ... NK a~NK~, where K is the number of nonzero terms in the polynomial, Ni and a~Ni~ (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.

Output

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

解决方法如下:

(一)利用map

#include<iostream>
#include<stdio.h>
#include<map>
using namespace std;

int main(){
	
	map<int,float> myMap;
	
	for(int i=0;i<2;i++){
		int n;
		cin>>n;
		
		int exp;
		float coe;//定义指数和系数
		for(int j=0;j<n;j++)
		{
			cin>>exp;
			cin>>coe;
			myMap[exp] += coe;	
		}
	} 
	
	map<int,float>::reverse_iterator it;
	int cnt = 0;
	for(it = myMap.rbegin();it != myMap.rend();it++)
		if(it->second != 0)//系数为0时不计入其中 
			cnt++;
	
	cout<<cnt;
	for(it = myMap.rbegin();it != myMap.rend();it++){
		if(it->second != 0)//系数为零时不打印 
			printf(" %d %.1f",it->first,it->second);//这里按题目要求要精度为1,需要这样打印才能全对 
	}
	
	return 0;
}

(二)使用数组进行操作

#include <stdio.h>
using namespace std;

int main(){
   float f[1001] = {0};
   
   int m;
   scanf("%d",&m);
   
   int a;
   float b;
   for(int i=0;i<m;i++){
		scanf("%d",&a);
		scanf("%f",&b);
		f[a] += b;
   }
   
   scanf("%d",&m);
   for(int i=0;i<m;i++){
		scanf("%d",&a);
		scanf("%f",&b);
		f[a] += b;
   }
   
   int cnt = 0;
   for(int i=0;i<1001;i++){
		if(f[i] != 0.0)
			cnt++;
   }
   
   printf("%d",cnt);
   for(int i=1000;i>=0;i--){
		if(f[i] != 0.0)
			printf(" %d %.1f",i,f[i]);//这里按题目要求要精度为1 
   }    

   return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/80887022