原题
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.
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
大体题意
A和B都是多项式,其中k表示项数,Ni表示指数,Ani表示系数,因此要将A和B相加,就是将有相同指数的项的系数相加。
注意若相加后系数为0,则不该显示此项了
还需注意最后输出的时候,指数的项先输出
思路
设置数组mp记录指数为n项的系数为mp[n]
此外设置set容器,用来存储系数不为0的项的指数
当输入A的多项式时,mp[n]+=a,然后判断若a==0则从set temp中删除,如果a!=0则添加入set。使用这个数组和set容器后,输入B的多项式也可以用同样操作
使用set的目的是即使添加入多次重复的数字,set具有去重功能,避免了麻烦
最后要求指数大的先输出,用两种方法,一种遍历set再保存在栈中,一种直接反向遍历set
set的具体使用在PAT基础知识
测试点问题,该题目要求保留一位小数,如果测试点1不通过很有可能是这个问题
这里就用到了
cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(1) << x;
头文件
#include <iomanip>
代码
#include <iostream>
using namespace std;
#include <set>
#include <stack>
#include <iomanip>
set<int> temp;
float mp[10001] = { 0 };
int main()
{
int ka, kb;
cin >> ka;
int n;
float a;
for (int i = 0; i < ka; i++)
{
cin >> n >> a;
mp[n] += a;
if (mp[n] == 0)
{
temp.erase(n);
}
else
{
temp.insert(n);
}
}
cin >> kb;
for (int i = 0; i < kb; i++)
{
cin >> n >> a;
mp[n] += a;
if (mp[n] == 0)
{
temp.erase(n);
}
else
{
temp.insert(n);
}
}
stack<int> s;
if (temp.size() != 0)
{
cout << temp.size();
for (auto it = temp.begin(); it != temp.end(); it++)
s.push(*it);
while (!s.empty())
{
int d = s.top();
s.pop();
cout << " " << d << " " << setiosflags(ios::fixed | ios::showpoint) << setprecision(1) << mp[d];
}
}
else
cout << "0" << endl;
return 0;
}