PAT1009 Product of Polynomials (25 分)

1009 Product of Polynomials (25 分)

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 N 1   a N 1   N 2   a N 2   . . .   N K   a N K N_1\ a_{N_1}\ N_2\ a_{N2}\ ...\ N_K\ a_{N_K}
where K is the number of nonzero terms in the polynomial, N i N​_i and a N i a_{N_i}
​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1 K 10 1≤K≤10 , 0 N K < < N 2 < N 1 1000 0≤N_K<⋯<N_2<N_1≤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




解析

这题要注意的是:多项式相乘后:有的项的系数可能为0.注意筛选。
多项式相乘:用双重循环相乘后,生成的多项式:可能指数不是按从大到小排序的。
比如说:
polynomial1 x 3 + x 1 x^3+x^1
polynomial2 x 100 + x 1 x^{100}+x^{1}
polynomial x 103 + x 4 + x 101 + x 2 x^{103}+x^{4}+x^{101}+x^{2}
无论用什么数据结构:都要注意这上面的两点哟。




Code:

#include<iostream>
#include<cstdio>
#include<vector>
#include<utility>
#include<algorithm>
using namespace std;
vector<pair<int, double>>::iterator _Find(vector<pair<int, double>>::iterator begin, vector<pair<int, double>>::iterator end,int val) {
	while (begin != end) {
		if (begin->first == val)
			return begin;
		begin++;
	}
	return end;
}
bool cmp(pair<int,double> p1,pair<int,double> p2) {
	return p1.first > p2.first;
}
int main()
{
	int N1, N2;
	cin >> N1;
	vector<pair<int, double>> po1(N1, make_pair(0, 0));
	for (int i = 0; i < N1; i++)
		cin >> po1[i].first >> po1[i].second;
	cin >> N2;
	vector<pair<int, double>> po2(N2, make_pair(0, 0));
	for (int i = 0; i < N2; i++)
		cin >> po2[i].first >> po2[i].second;
	vector<pair<int, double>> po;
	int exponents;
	double coefficient;
	for (int i = 0; i < N1; i++) {
		for (int j = 0; j < N2; j++) {
			exponents = po1[i].first + po2[j].first;
			coefficient = po1[i].second*po2[j].second;
			auto it = _Find(po.begin(), po.end(), exponents);
			if (it == po.end())
				po.push_back(make_pair(exponents, coefficient));
			else
				it->second += coefficient;
		}
	}
	int len=0;
	for (auto x : po)
		if (x.second != 0)
			len++;
	sort(po.begin(),po.end(), cmp);
	cout << len;
	for (auto it = po.cbegin(); it != po.cend(); it++) {
		if(it->second!=0)
			printf(" %d %.1f", it->first, it->second);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41256413/article/details/82811064