当前位置: 代码迷 >> 综合 >> C++ Pat甲级1009?Product of Polynomials?(25 分)
  详细解决方案

C++ Pat甲级1009?Product of Polynomials?(25 分)

热度:51   发布时间:2023-11-17 22:38:59.0

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????

where K is the number of nonzero terms in the polynomial, N?i?? and a?N?i???? (i=1,2,?,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10, 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

 输入两行:项数N  每项的指数Ni,系数aNi

输出 :两多项式乘积 ,项数N  每项的指数Ni,系数aNi

#include<cmath>
#include<cstdio>
#include<vector>
#include<iostream>
using namespace std;
//pair的两个属性值  first  和second 
#define fi first
#define se second
int main()
{int n,k;double m;double p[2000+5] = {0};     //乘积的最大项的次数为2000vector<pair<double,int> > a;//相当于在容器里存了一个struct类型 vector<pair<double,int> > b;//输入两个多项式 cin >> n;while (n--){cin >> k >> m;a.push_back(make_pair(m,k));}cin >> n;while (n--){cin >> k >> m;b.push_back(make_pair(m,k));}// 每项分别相乘,两重循环 for (int i = 0 ; i < a.size() ; i++){for (int j = 0 ; j < b.size() ; j++){p[a[i].se + b[j].se] += a[i].fi * b[j].fi;//p[指数]中存的是对应指数的系数 }}//将a的内容删除,将p中系数不为0的项存入a a.clear();for (int i = 2000 ; i >= 0 ; i--){if (fabs(p[i]) >= 0.05){a.push_back(make_pair(p[i],i));}}
//输出结果cout << a.size();for (int i = 0 ; i < a.size() ; i++)printf (" %d %.1lf",a[i].se,a[i].fi);cout << endl;return 0;
}

C++中pair的使用方法 https://blog.csdn.net/oceanlight/article/details/7890537

pair 和 make_pair 的使用 https://blog.csdn.net/hiwoshixiaoyu/article/details/53894162

多项式加法:

	// 每项分别相加,两重循环for (int i = 0 ; i < a.size() ; i++) {for (int j = 0 ; j < b.size() ; j++) {if(a[i].se == b[j].se) {p[a[i].se + b[j].se] = a[i].fi + b[j].fi;//p[指数]中存的是对应指数的系数}else if(a[i].se != 0){p[a[i].se] = a[i].fi;}else if(b[j].se != 0){p[b[j].se] = b[j].fi;}}}

 

  相关解决方案