一开始用c语言写特别麻烦,最近学了c++,c++写这题挺简单的
题目如下:
它要求我们降序输出,且多项式相乘相加无重复项,我们可以用map来写这道题
//用map容器来写这道题,map能自动排序
#include<iostream>
#include<map>
using namespace std;
class comPare {//一个降序的仿函数
public:
bool operator()(int v1, int v2) const{
return v1 > v2;
}
};
int main() {
map<int, int,comPare>m1,m2,result;
map<int, int,comPare>::iterator it1, it2;
int n;
cin >> n;
while (n--) {
int x1, x2;
cin >> x1 >> x2;
m1[x2] = x1; //注意题目中指数在第二个,我们得把它放在key值
}
cin >> n;
while (n--) {
int x1, x2;
cin >> x1 >> x2;
m2[x2] = x1;
}
for (it1 = m1.begin(); it1 != m1.end(); it1++) { //用一个多项式的每一项去乘另外一个多项式,结果放到第三个map中
for(it2 = m2.begin(); it2 != m2.end(); it2++) {
int re1, re2;
re1 = (it1->first) + (it2->first), re2 = (it1->second) * (it2->second);
if (result.find(re1) == result.end()) {//没找到直接添加
result[re1] = re2;
}
else if (result[re1] + re2 != 0) {
result[re1] += re2;
}
else {
result.erase(re1);//为0就直接删除这一项
}
}
}
if (result.size() == 0) {//零多项式按要求输出
cout << "0 0" << endl;
}
else {
int i = 0;
for (map<int, int, comPare>::iterator it = result.begin(); it != result.end(); it++, i++) {
if (i > 0) cout << " ";
cout << it->second << " " << it->first;
}
cout << endl;
}
for (it2 = m2.begin(); it2 != m2.end(); it2++) {
if (m1.find(it2->first) == m1.end()) {
m1.insert(pair<int, int>(it2->first, it2->second));
}
else {
int re2,re1;
re1 = it2->first;
re2 = m1[re1] + (it2->second);
if (re2 == 0) {
m1.erase(re1);//为0删除
}else{
m1[re1]=re2;
}
}
}
if (m1.size() == 0) {
cout << "0 0" << endl;
}
else {
int i = 0;
for (map<int, int, comPare>::iterator it3 = m1.begin(); it3 != m1.end(); it3++, i++) {
if (i > 0) cout << " ";
cout << it3->second << " " << it3->first;
}
cout << endl;
}
return 0;
}
提交结果: