fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <map>
  4. #include <cctype>
  5. #include <string>
  6.  
  7. int main() {
  8. std::string line;
  9. while (std::getline(std::cin, line)) {
  10. std::map<std::string, int> terms;
  11. std::istringstream iss(line);
  12. std::string token;
  13. int constant = 0;
  14.  
  15. while (iss >> token) {
  16. int sign = 1;
  17. if (token == "+") continue;
  18. if (token == "-") {
  19. sign = -1;
  20. iss >> token;
  21. }
  22.  
  23. size_t i = 0;
  24. while (i < token.size() && (isdigit(token[i]) || token[i] == '-')) i++;
  25. int coeff = 1;
  26. if (i > 0) coeff = std::stoi(token.substr(0, i));
  27. std::string var = token.substr(i);
  28.  
  29. if (var.empty()) {
  30. constant += sign * coeff;
  31. } else {
  32. terms[var] += sign * coeff;
  33. }
  34. }
  35.  
  36. std::ostringstream oss;
  37. bool first = true;
  38. for (const auto& [var, coeff] : terms) {
  39. if (coeff == 0) continue;
  40. if (!first && coeff > 0) oss << " + ";
  41. else if (coeff < 0) oss << " - ";
  42. else if (!first) oss << " + ";
  43.  
  44. if (abs(coeff) != 1) oss << abs(coeff);
  45. else if (coeff == -1 && first) oss << "-";
  46. oss << var;
  47. first = false;
  48. }
  49.  
  50. if (constant != 0) {
  51. if (!first && constant > 0) oss << " + ";
  52. else if (constant < 0) oss << " - ";
  53. else if (!first) oss << " + ";
  54. oss << abs(constant);
  55. }
  56.  
  57. std::string result = oss.str();
  58. if (result.empty()) result = "0";
  59. std::cout << result << std::endl;
  60. }
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 5320KB
stdin
1
11
3
1 2a1b1
3
1 1a2b0
3
2 1a0b2
3
2 1a5b1
3
1 1a2b0
3
stdout
1
11
3
2a1b1 + 1
3
a2b0 + 1
3
a0b2 + 2
3
a5b1 + 2
3
a2b0 + 1
3