题目不贴了,解题思路如下
1.定义一个包含幂和系数的类,定义该类的3个vector,分别存储第一行和第二行数据,结果
2.处理过程,分别取容器中的幂进行比较,思想有点类似于归并排序中的合并步骤,幂大的先输出,相同的相加输出。
4.该算法复杂度为O(K1 + K2)
3.输出的时候逆序输出答案即可
坑点:
1.系数AN要特别注意,为0的不能输出该结果,非常重要,很容易忽略!!!!!同时还要注意doube型是否为0的判断
2.最后一点就是如果最后无结果的话,一定要输出个“0”,无输出结果!!!第6个测试点会判错,非常坑!!!
PS:这道题由于本人的水平,提交了好几次,都是部分正确,最后才弄对。中间被题目带偏,因为AN题目并没有规定范围,我以为是个大数!!!!!捉急!!!后来才进入正轨!!
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <sstream>
#define MIN_FLAG -1
#define TEST 0
using namespace std;
struct p{
int e;
double an;
p(): e(0), an(0) {}
};
vector<p> ary1;
vector<p> ary2;
vector<p> ans;
int length1;
int length2;
const double esp = 1e-9;
int is_end(int &i, int &j)
{
if(i + j == length2 + length1)
return 1;
return 0;
}
int is_zero(double i)
{
if((i >= -esp && i <= esp))
return 1;
return 0;
}
int main(void)
{
int flag = 0;
string line;
p temp;
#if TEST
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
while(getline(cin, line))
{
ary1.clear();
ary2.clear();
ans.clear();
if(flag % 2 == 0)
{
stringstream ss(line);
ss >> length1;
for(int i = 0; i < length1; i++)
{
ss >> temp.e;
ss >> temp.an;
ary1.push_back(temp);
}
/*we need the end flag*/
temp.e = MIN_FLAG;
ary1.push_back(temp);
}
else
{
stringstream ss(line);
ss >> length2;
for(int i = 0; i < length2; i++)
{
ss >> temp.e;
ss >> temp.an;
ary2.push_back(temp);
}
/*we need the end flag*/
temp.e = MIN_FLAG;
ary2.push_back(temp);
}
if(flag % 2 == 1)
{
int i = 0;
int j = 0;
while(1)
{
if(ary1[i].e == ary2[j].e)
{
/*skip 0*/
temp.an = ary1[i].an + ary2[j].an;
temp.e = ary1[i].e;
i++;
j++;
if(is_zero(temp.an)) //坑点之一
{
if(is_end(i ,j))
break;
continue;
}
ans.push_back(temp);
}
else if(ary1[i].e > ary2[j].e)
{
temp.an = ary1[i].an;
temp.e = ary1[i].e;
i++;
if(is_zero(temp.an))
{
if(is_end(i ,j))
break;
continue;
}
ans.push_back(temp);
}
else
{
temp.an = ary2[j].an;
temp.e = ary2[j].e;
j++;
if(is_zero(temp.an))
{
if(is_end(i ,j))
break;
continue;
}
ans.push_back(temp);
}
if( i + j == length1 + length2)
{
break;
}
}
/*output*/
cout << ans.size(); //这里输出的时候,千万要注意
for(unsigned int i = 0; i < ans.size(); i++)
{
cout << " " << ans[i].e;
cout << " ";
printf("%.1f", ans[i].an);
}
cout << "\n";
}
flag++;
}
return 0;
}