设计函数分别求两个一元多项式的乘积与和。
输入格式:
输入分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
这道题之前做过,但。。忘了,写的还没之前写的好,不过和刚开始的思路差不多,上来无脑想的是map,参考上次的做法,又写成了这个样子,以指数作为唯一标识,即作为键,因为指数最终具有唯一性,而系数不一定。再有就是关于范围的问题,题目中说系数和指数的绝对值范围不超过1000,则相乘时由于指数相加,所以最大为2000,最小为-2000,而相加时,指数保持不变(合并同类项时),所以最大为1000,最小为-1000
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int n,coef,expo;
map<int,int> m1,m2;
vector<pair<int,int> > v1,v2;
cin >> n;
while(n--){
cin >> coef >> expo;
v1.push_back(make_pair(expo,coef));
}
cin >> n;
while(n--){
cin >> coef >> expo;
v2.push_back(make_pair(expo,coef));
}
//乘法
for(auto it = v1.begin();it!=v1.end();it++){
for(auto itt = v2.begin();itt!=v2.end();itt++){
expo = it->first + itt->first;
coef = it->second * itt->second;
m1[expo] += coef;
}
}
bool flag = false;
for(int i = 2000;i>=-2000;i--){
if(m1[i]){
if(!flag){
cout << m1[i] << " " << i;
flag = true;
}else{
cout << " " << m1[i] << " " << i;
}
}
}
if(!flag)
cout << "0 0";
cout << endl;
//加法
for(auto it = v1.begin();it!=v1.end();it++){
m2[it->first] += it->second;
}
for(auto it = v2.begin();it!=v2.end();it++){
m2[it->first] += it->second;
}
flag = false;
for(int i = 1000;i>=-1000;i--){
if(m2[i]){
if(!flag){
cout << m2[i] << " " << i;
flag = true;
}else{
cout << " " << m2[i] << " " << i;
}
}
}
if(!flag)
cout << "0 0";
return 0;
}