Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 1002. A+B for Polynomials

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

解答

#include <cstdio>
#include <cmath>
#include <map>
using namespace std;

struct cmp { bool operator()(const int &x, const int &y) { return x > y; } };

int main()
{
	map<int, double, cmp> a, b, c;

	int n, t1; double t2;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) scanf("%d%lf", &t1, &t2), a[t1] = t2;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) scanf("%d%lf", &t1, &t2), b[t1] = t2;

	map<int, double, cmp>::iterator pa = a.begin(), pb = b.begin(), pc;
	while (pa != a.end() && pb != b.end())
		if (pa->first == pb->first)
		{
			if (fabs(pa->second + pb->second) < 1e-6)
				pa++, pb++;
			else 
				c[pa->first] = pa->second + pb->second, pa++, pb++;
		}
		else if(pa->first < pb->first)
			c[pb->first] = pb->second, pb++;
		else
			c[pa->first] = pa->second, pa++;

	while (pa != a.end()) c[pa->first] = pa->second, pa++;
	while (pb != b.end()) c[pb->first] = pb->second, pb++;  

	printf("%d", c.size());
	for (pc = c.begin(); pc != c.end(); pc++)
	    printf(" %d %.1f", pc->first, pc->second);
	printf("\n");

	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论