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

PAT 1009. Product of Polynomials

This time, you are supposed to find A*B where A and B are two polynomials.

Input Specification

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 Specification

For each test case you should output the product 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 up to 1 decimal place.

Sample Input

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output

3 3 3.6 2 6.0 1 1.6

解答

#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, pb, pc;
	for (pa = a.begin(); pa != a.end(); pa++)
		for (pb = b.begin(); pb != b.end(); pb++)
			c[pa->first+pb->first] += pa->second * pb->second;

	for (pc = c.begin(); pc != c.end();)
		if (fabs(pc->second) > 1e-6)
			pc++;
		else
			c.erase(pc++); //移除系数0,先把pc自增,然后把原pc指向的值删除

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

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

我的博客

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

站内搜索

最新评论