PAT 1009

指数相加,系数相乘

参考 1002


#include 
#include 
#include 
using namespace std;

map S1;
map S2;
map S3;
int g_K = 0;//S3的项数

void input()
{
	int K;
	cin >> K;
	while (--K >= 0)
	{
		int N;
		float A;
		cin >> N >> A;
		S1.insert(pair(N, A));
	}

	cin >> K;
	while (--K >= 0)
	{
		int N;
		float A;
		cin >> N >> A;
		S2.insert(pair(N, A));
	}
	return;
}

void func()
{
	int cFirst;
	float cSecond;
	for (auto a : S1)
	{
		for (auto b : S2)
		{
			cFirst = a.first + b.first;
			cSecond = a.second * b.second;
			map::iterator ite = S3.find(cFirst);
			if (ite != S3.end())//指数已经存在,系数相加
			{
				ite->second += cSecond;
			}
			else
			{
				S3.insert(pair(cFirst, cSecond));
			}
		}
	}

	map::iterator p;
	for (p = S3.begin(); p != S3.end(); )
	{
		if (fabs(p->second) < 0.00001)
		{
			map::iterator temp = p;
			++p;
			S3.erase(temp);
			continue;
		}
		++p;
		++g_K;
	}
}

int main()
{
	input();
	func();
	cout << g_K;
	map::reverse_iterator iter;
	for (iter = S3.rbegin(); iter != S3.rend(); iter++)
	{
		cout << ' ' << iter->first << ' ';
		printf("%.1f", iter->second);
	}
	cout << endl;
	return 0;
}


你可能感兴趣的:(PAT)