算法:multimap
注意:
①求和后系数为0时,不计算其项数。
②精确度。
#include <iostream>
#include <map>
#include <math.h>
using namespace std;
multimap<int, float> S1;
map<int, float> S2;
int g_K = 0;//S3的项数
void input()
{
int K;
cin >> K;
while (--K >= 0)
{
int N;
float A;
cin >> N >> A;
S1.insert(pair<int, float>(N, A));
}
cin >> K;
while (--K >= 0)
{
int N;
float A;
cin >> N >> A;
S1.insert(pair<int, float>(N, A));
}
return;
}
void func()
{
for (auto c : S1)
{
if (S2.find(c.first) != S2.end())//已经计算过了
continue;
float sum = 0.0;
for (auto beg = S1.lower_bound(c.first),
end = S1.upper_bound(c.first);
beg != end; ++beg)
{
sum += beg->second;
}
if (fabs(sum) < 0.00001)///和为0,则不计入项数
{
}
else
{
S2.insert(pair<int, float>(c.first, sum));
g_K++;
}
}
}
int main()
{
input();
func();
cout << g_K;
map<int, float>::reverse_iterator iter;
for (iter = S2.rbegin(); iter != S2.rend(); iter++)
{
cout << ' ' << iter->first << ' ';
printf("%.1f", iter->second);
}
cout << endl;
return 0;
}