看了一圈答案没有用STD Map解的,自己写踩了不少坑,尤其是当系数等于1….属实是没想到了

中间很多代码重复的,懒得再解耦了

#include <bits/stdc++.h>

int main() {
std::map<long long, long long> final;
for (int i = 0; i < 2; ++i) {
std::string result = "";
while (true) {
long long a, b;
std::cin >> a >> b;
// 判断是否结束
if (a == 0 && b == -1) {
break;
}

if (a == 0) {
continue;
}
// 判断该指数是否存在
if (final.find(b) == final.end()) {
final.insert(std::make_pair(b, a));
} else {
long long new_a = final.find(b)->second + a;
if (new_a == 0) {
final.erase(b);
} else {
final.find(b)->second = new_a;
}
}

// 判断是否为第一项,不是则加+号
if (result.length() != 0 && a > 0) {
result = result.append("+");
}
// 判断是否为常数项
if (b == 0) {
result = result.append(std::to_string(a));
continue;
}

if (b == 1) {
if (a == 1) {
result = result.
append("X");
continue;
} else if (a == -1) {
result = result.
append("-X");
continue;
}

result = result.
append(std::to_string(a)).
append("X");
} else {

if (a == 1) {
result = result.
append("X^").
append(std::to_string(b));
continue;
} else if (a == -1) {
result = result.
append("-X^").
append(std::to_string(b));
continue;
}

result = result.
append(std::to_string(a)).
append("X^").
append(std::to_string(b));
}
}
if (result.length() == 0) {
result = "0";
}
std::cout << result << std::endl;
}

std::map<long long, long long>::reverse_iterator iterator;
std::string result = "";

for (iterator = final.rbegin(); iterator != final.rend(); iterator++) {
if (iterator != final.rbegin() && iterator->second > 0) {
result = result.append("+");
}

if (iterator->first == 0) {
result = result.append(std::to_string(iterator->second));
continue;
}

if (iterator->first == 1) {
if (iterator->second == 1) {
result = result.
append("X");
continue;
} else if (iterator->second == -1) {
result = result.
append("-X");
continue;
}

result = result.
append(std::to_string(iterator->second)).
append("X");
} else {

if (iterator->second == 1) {
result = result.
append("X^").
append(std::to_string(iterator->first));
continue;
} else if (iterator->second == -1) {
result = result.
append("-X^").
append(std::to_string(iterator->first));
continue;
}


result = result.
append(std::to_string(iterator->second)).
append("X^").
append(std::to_string(iterator->first));
}
}

if (result.length() == 0) {
result = "0";
}

std::cout << result << std::endl;

return 0;
}