Description
Oaiei is a good boy who loves math very much, he would like to simplify some mathematical expression, can you help him? For the sake of simplicity, the form of expression he wanted to simplify is shown as follows:
- General characters
- num: an integer (0 <= num <= 1000)
- X: unknown variable
- X^num: num power of X
- numX: the coefficient of the unknown variable X is num
- Connector character
- +: General characters connected with the character which expresses the addition
- -: General characters connected with the character which expresses the subtraction
Input
Given the expression S, the length of S is less than 200, there is no space in the given string.
Output
Output the simplest expression S’, you should output S’ accordance to the X with descending order of power. Note that X^1 need only output X, 1X need only output X.
Sample Input
4X^5+8X^5+4X+3X^0+8
-4X^5-3X^5
Sample Output
12X^5+4X+11
-7X^5
同时,注意输出
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
string s;
string tag;
vector<int> po;
map<int, int> ans;
void todo()
{
int i = 0, len = tag.length();
int con = 1;
int num = 0;
int pow = 0;
if(tag[i] == '-') {con = -1; i++;}
if(tag[i] == '+') {con = 1; i++;}
while(i < len) {
if(tag[i] == 'X') {
num = 1;
}
else {
while(i < len && tag[i] >= '0' && tag[i] <= '9') {
num = num * 10 + tag[i++] - '0';
}
}
if(i < len) {
pow = 1;
i++;
if(i < len) {
i++;
pow = 0;
while(i < len) pow = pow * 10 + tag[i++] - '0';
}
}
}
if(ans.count(pow)) ans[pow] += (con*num);
else {
ans[pow] = (con*num);
po.push_back(pow);
}
}
void deal()
{
tag.clear();
int tot = 0;
int len = s.length();
do {
tag += s[tot++];
while(tot < len && s[tot] != '+' && s[tot] != '-') {
tag += s[tot++];
}
todo();
tag.clear();
}while(tot < len);
}
void print()
{
int flag = 0;
for(int i = po.size()-1; i >= 0; --i) {
if(ans[po[i]] == 0) continue;
if((ans[po[i]] == 1 || ans[po[i]] == -1) && po[i] != 0) {
if(flag && ans[po[i]] == 1) printf("+");
else if(ans[po[i]] == -1) printf("-");
}
else {
if(flag && ans[po[i]] > 0) printf("+");
printf("%d", ans[po[i]]);
}
flag = 1;
if(po[i] == 0) continue;
printf("X");
if(po[i] == 1) continue;
printf("^%d", po[i]);
}
if(!flag) printf("0");
printf("\n");
}
int main()
{
// freopen("in", "r", stdin);
while(cin >> s) {
po.clear();
ans.clear();
deal();
sort(po.begin(), po.end());
print();
}
return 0;
}