题目描述:
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 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
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
题目大意:给出两个多项式,计算这两个多项式的和并输出。注意多项式相加规则,系数相同的一项指数相加。
题目思路:此题可使用hash思想,将指数作为地址,系数作为存放内容。(注意数组数据类型是double。)
参考代码:
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 1010;
double p[MAXN] = { 0.0 };
int main()
{
int n;
memset(p, 0, sizeof(p));
for (int i = 0; i < 2; i++)
{
cin >> n;
for (int j = 0; j < n; j++)
{
int a;
double b;
cin >> a >> b;
if (p[a] == 0.0) p[a] = b;
else
{
p[a] += b;
}
}
}
int cnt =0;
for (int i = 0; i < MAXN; i++)
{
if (p[i] != 0.0) cnt++;
}
cout << cnt;
for (int i = MAXN; i >= 0; i--)
{
if (p[i] != 0.0) {
printf(" %d %.1f", i, p[i]);
}
}
cout << endl;
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。