- 题目:
- 思路:
首先通过getline得到A和B两行的字符串,并且对这两行的字符串进行解析,将系数和指数分别提取出来通过一个结构体,然后存入map结构中,存入的时候就进行判断,如果map中已经存在对应指数的数据,就将指数部分相加再存入,因为map结构是有序的所以已经排列好顺序了,直接输出就行
- 易错点:
不要忽略系数为0的时候不输出的情况
- 代码:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <map>
using namespace std;
stringstream ss;
typedef struct
{
int exp;
double res;
}Polynomial;
map<int,double> pol_map;
bool search_pol(Polynomial pol)
{
for (auto it = pol_map.begin(); it != pol_map.end(); it++)
{
if ((*it).first == pol.exp)
{
(*it).second += pol.res;
return true;
}
}
return false;
}
void split_pol(char pol[])
{
int i = 2;
int flag = 1;
Polynomial pol_tmp;
while (pol[i] != '\0')
{
char tmp[10] = "";
int k = 0;
if (pol[i] == 32)
{
i++;
continue;
}
for (; pol[i] != 32 && pol[i] != '\0'; i++)
{
tmp[k] = pol[i];
k++;
}
if (flag % 2 != 0)
pol_tmp.exp = atoi(tmp);
else
{
pol_tmp.res = atof(tmp);
if(!search_pol(pol_tmp))
pol_map.insert(pair<int,double>(pol_tmp.exp,pol_tmp.res));
}
flag++;
}
return;
}
int main()
{
char A[1000], B[1000];
int size = 0;
cin.getline(A, 1000);
cin.getline(B,1000);
split_pol(A);
split_pol(B);
for (auto it = pol_map.begin(); it != pol_map.end(); ++it)
{
if ((*it).second == 0)
continue;
++size;
}
ss << size;
for (auto it = pol_map.rbegin(); it != pol_map.rend(); ++it)
{
if ((*it).second == 0)
continue;
ss << " ";
ss << (*it).first;
ss << " ";
ss << fixed << setprecision(1) << (*it).second;
}
cout << ss.str();
return 0;
}