1002 A+B for Polynomials (25分)

题目描述

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:

在这里插入图片描述

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时不进行输出。
  • 我们只需要开辟一个数组,让指数做index,系数放在数组中,若指数相同(index相同),则系数相加(a[index]+= 系数)
#include 
#include 

using namespace std;
void Read(double a[]);
int main()
{
	int N,i,count = 0;
	double a[1001];
	// 对a进行初始化 为0 
	memset(a,0,sizeof(a));
	Read(a);
	Read(a);
	for(i = 0;i < 1001;i++)
	{
		if(a[i]!=0)
		{
			count++;
			
		}
	}
	printf("%d",count);
	
	for(i = 0;i < 1001;i++)
	{
		if(a[i]!=0){
			// 保留一位小数 
			printf(" %d %.1f",i,a[i]);
		}
			
	}
	
}
void Read(double a[])
{
	int i,N;
	int exp;
	double coef;
	scanf("%d",&N);
	for(i = 0; i < N;i++)
	{
		scanf("%d%lf",&exp,&coef);
		// 指数相同时,系数相加
		a[exp] += coef;
	}
	
}

你可能感兴趣的:(数据结构)