版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
7-2 一元多项式的乘法与加法运算 (20 分)
设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。零多项式应输出0 0
。
输入样例:
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例:
15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0
#include<iostream>
#include <map>
using namespace std;
void input(map<int, int, greater<int>>& mp) {
int t, e, n;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> t >> e;
mp[e] = t;
}
}
void output(const map<int, int, greater<int>>& mp) {
bool flag = false;
for (auto& it : mp) {
if (it.second) {
cout << (flag ? " " : "") << it.second << " " << it.first ;
flag = true;
}
}
cout << (flag ? "" : "0 0") << endl;
}
int main(){
map<int, int,greater<int>> a, b, add, mult;
int n, flag = 0;
input(a); input(b);
add = a;
for (auto& it : b)
add[it.first] += it.second;
for (auto& i : a) {
for (auto& j : b) {
mult[i.first + j.first] += i.second * j.second;
}
}
output(mult); output(add);
return 0;
}