1002. A+B for Polynomials (25)
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 思路 题目要求打印两个多项式相加后的多项式的指数和系数。 用map<指数,系数>这样的关联形式来模拟相加就很简单了,找到对应的指数(键)计算对应的系数(值)就行。
特别注意的情况:指数的系数相加如果为0,那么这个指数和其对应的系数就不用输出了(相消了),而且对应的第一个输出的数字——指数个数也要减1。 代码
#include<iostream>
#include<map>
#include<iomanip>
#include<iterator>
using namespace std;
int main()
{
int k1,ksum = ;
while(cin >> k1)
{
map<int,double> sum; //<指数,系数>
for(int i = ;i < k1;i++)
{
int n;double a;
cin >> n >> a;
sum.insert(pair<int,double>(n,a));
ksum++;
} int k2;
cin >> k2;
for(int i = ;i < k2;i++)
{
int n;double a;
cin >> n >> a;
if(sum.count(n) > )
{
sum[n] += a;
if(sum[n] == )
ksum--;
}
else
{
sum.insert(pair<int,double>(n,a));
ksum++;
} } cout << ksum;
for(map<int,double>::reverse_iterator it = sum.rbegin(); it != sum.rend();it++)
{
if(it->second != )
{
cout << " " << it->first;
cout <<" "<< fixed << setprecision() << it->second;
} }
cout << endl;
}
}