<p>Given an expression such as <code>expression = &quot;e + 8 - a + 5&quot;</code> and an evaluation map such as <code>{&quot;e&quot;: 1}</code> (given in terms of <code>evalvars = [&quot;e&quot;]</code> and <code>evalints = [1]</code>), return a list of tokens representing the simplified expression, such as <code>[&quot;-1*a&quot;,&quot;14&quot;]</code></p>

<ul>
	<li>An expression alternates chunks and symbols, with a space separating each chunk and symbol.</li>
	<li>A chunk is either an expression in parentheses, a variable, or a non-negative integer.</li>
	<li>A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like <code>&quot;2x&quot;</code> or <code>&quot;-x&quot;</code>.</li>
</ul>

<p>Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.</p>

<ul>
	<li>For example, <code>expression = &quot;1 + 2 * 3&quot;</code> has an answer of <code>[&quot;7&quot;]</code>.</li>
</ul>

<p>The format of the output is as follows:</p>

<ul>
	<li>For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
	<ul>
		<li>For example, we would never write a term like <code>&quot;b*a*c&quot;</code>, only <code>&quot;a*b*c&quot;</code>.</li>
	</ul>
	</li>
	<li>Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
	<ul>
		<li>For example, <code>&quot;a*a*b*c&quot;</code> has degree <code>4</code>.</li>
	</ul>
	</li>
	<li>The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.</li>
	<li>An example of a well-formatted answer is <code>[&quot;-2*a*a*a&quot;, &quot;3*a*a*b&quot;, &quot;3*b*b&quot;, &quot;4*a&quot;, &quot;5*c&quot;, &quot;-6&quot;]</code>.</li>
	<li>Terms (including constant terms) with coefficient <code>0</code> are not included.
	<ul>
		<li>For example, an expression of <code>&quot;0&quot;</code> has an output of <code>[]</code>.</li>
	</ul>
	</li>
</ul>

<p><strong>Note:</strong> You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> expression = &quot;e + 8 - a + 5&quot;, evalvars = [&quot;e&quot;], evalints = [1]
<strong>Output:</strong> [&quot;-1*a&quot;,&quot;14&quot;]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> expression = &quot;e - 8 + temperature - pressure&quot;, evalvars = [&quot;e&quot;, &quot;temperature&quot;], evalints = [1, 12]
<strong>Output:</strong> [&quot;-1*pressure&quot;,&quot;5&quot;]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> expression = &quot;(e + 8) * (e - 8)&quot;, evalvars = [], evalints = []
<strong>Output:</strong> [&quot;1*e*e&quot;,&quot;-64&quot;]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= expression.length &lt;= 250</code></li>
	<li><code>expression</code> consists of lowercase English letters, digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;*&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39; &#39;</code>.</li>
	<li><code>expression</code> does not contain any leading or trailing spaces.</li>
	<li>All the tokens in <code>expression</code> are separated by a single space.</li>
	<li><code>0 &lt;= evalvars.length &lt;= 100</code></li>
	<li><code>1 &lt;= evalvars[i].length &lt;= 20</code></li>
	<li><code>evalvars[i]</code> consists of lowercase English letters.</li>
	<li><code>evalints.length == evalvars.length</code></li>
	<li><code>-100 &lt;= evalints[i] &lt;= 100</code></li>
</ul>

class Solution {
private:
    class list_node {
    public:
        list_node *prev;
        list_node *next;

        list_node() {
            prev = next = nullptr;
        }

        virtual ~list_node() { }
    };

    class list_head {
    public:
        list_node   *head;
        list_node   *tail;

        list_head() {
            head = tail = nullptr;
        }

        void insert_after(list_node *prev, list_node *n) {
            if (prev == nullptr) {
                n->next = head;
                head = n;
            } else {
                n->next = prev->next;
                prev->next = n;
            }
            n->prev = prev;
            if (n->next == nullptr)
                tail = n;
            else
                n->next->prev = n;
        }

        void insert_after(list_node *prev, list_node *first, list_node *last) {
            if (prev == nullptr) {
                last->next = head;
                head = first;
            } else {
                last->next = prev->next;
                prev->next = first;
            }
            first->prev = prev;
            if (last->next == nullptr)
                tail = last;
            else
                last->next->prev = last;
        }

        void remove(list_node *first, list_node *last) {
            if (first->prev == nullptr)
                head = last->next;
            else
                first->prev->next = last->next;
            if (last->next == nullptr)
                tail = first->prev;
            else
                last->next->prev = first->prev;
        }
    };

    struct hash_str {
        size_t operator()(const string *s) const {
            return hash<string>()(*s);
        }
    };

    struct cmp_str {
        bool operator()(const string *s1, const string *s2) const {
            return equal_to<string>()(*s1, *s2);
        }
    };

    typedef unordered_map<string *, int, hash_str, cmp_str> evalmap;

    class node : public list_node {
    public:
        int         coeff;
        string      name;
        char        op;
        int         degree;
        list_head   subexpr;

        node() = default;

        node(char operation) {
            coeff = 0;
            op = operation;
        }

        node(string&& s) {
            coeff = 1;
            name = s;
            op = 0;
        }

        node(int c) {
            coeff = c;
            op = 0;
        }

        node(int c, string&& s) {
            coeff = c;
            name = s;
            op = 0;
        }

        node(list_head&& ls) {
            coeff = 1;
            op = 0;
            subexpr = ls;
        }

        node(int c, string&& s, char operation) {
            coeff = c;
            name = s;
            op = operation;
        }

        void setDegree() {
            int i, n;

            n = name.size();

            if (n == 0) {
                degree = 0;
                return;
            }

            degree = 1;
            for (i = 0; i < n; i++) {
                if (name[i] == '*')
                    ++degree;
            }
        }
    };

    class entry {
    public:
        int         coeff;
        string      name;
        char        op;
        int         degree;
        list_head   subexpr;

        entry() = default;

        entry(int c, string *nm, char operation, int d, list_head sub) {
            coeff = c;
            name = *nm;
            op = operation;
            degree = d;
            subexpr = sub;
        }
    };

    struct node_cmp {
        bool operator()(const entry *e1, const entry *e2) const {
            const char *s1, *s2;

            if (e1->degree != e2->degree)
                return e1->degree < e2->degree;

            if (e1->name.size() == 0)
                s1 = nullptr;
            else {
                s1 = e1->name.c_str();
                if (*s1 == '-')
                    ++s1;
                while (isdigit(*s1))
                    ++s1;
            }

            if (e2->name.size() == 0)
                s2 = nullptr;
            else {
                s2 = e2->name.c_str();
                if (*s2 == '-')
                    ++s2;
                while (isdigit(*s2))
                    ++s2;
            }

            if (s1 == nullptr) {
                if (s2 == nullptr)
                    return e1->coeff > e2->coeff;
                return false;
            }
            if (s2 == nullptr)
                return true;

            return strcmp(s1, s2) > 0;
        }
    };

    struct entry_cmp {
        int dir;

        bool operator()(const entry *e1, const entry *e2) const {
            const char *s1, *s2;
            int cmp;

            if (e1->name.size() == 0)
                s1 = nullptr;
            else {
                s1 = e1->name.c_str();
                if (*s1 == '-')
                    ++s1;
                while (isdigit(*s1))
                    ++s1;
            }

            if (e2->name.size() == 0)
                s2 = nullptr;
            else {
                s2 = e2->name.c_str();
                if (*s2 == '-')
                    ++s2;
                while (isdigit(*s2))
                    ++s2;
            }

            if (s1 == nullptr) {
                if (s2 == nullptr)
                    return dir == -1 ? e1->coeff < e2->coeff : e1->coeff > e2->coeff;
                return dir == -1;
            }
            if (s2 == nullptr)
                return dir == 1;

            cmp = strcmp(s1, s2);
            return dir == -1 ? cmp < 0 : cmp > 0;
        }
    };

    list_head parseExpr(string& s, int& startidx, evalmap& tbl) {
        evalmap::iterator it;
        int i, j;
        int n;
        list_head ret;
        node *expr, *prev;

        n = s.length();

        prev = nullptr;
        i = startidx;
        for (;;) {
            char c;
            int val;

            c = s[i];
            if (c == ' ') {
                ++i;
                continue;
            }
            if (c == ')') {
                ++i;
                break;
            }
            if (isalpha(c)) {
                string nm;

                for (j = i + 1; j < n; j++) {
                    if (!isalpha(s[j]))
                        break;
                }
                nm = string(s, i, j - i);
                it = tbl.find(&nm);
                if (it == end(tbl)) {
                    expr = new node(std::move(nm));
                    if (prev != nullptr && prev->op == '-') {
                        prev->op = '+';
                        expr->coeff *= -1;
                    }
                } else {
                    val = it->second;
                    if (prev != nullptr && prev->op == '-') {
                        prev->op = '+';
                        val = -val;
                    }
                    expr = new node(val);
                }
                i = j;
            } else if (isdigit(c)) {
                val = c - '0';
                for (j = i + 1; j < n; j++) {
                    c = s[j];
                    if (!isdigit(c))
                        break;
                    val *= 10;
                    val += c - '0';
                }
                if (prev != nullptr && prev->op == '-') {
                    prev->op = '+';
                    val = -val;
                }
                expr = new node(val);
                i = j;
            } else if (c == '(') {
                ++i;
                if (prev != nullptr && prev->op == '-') {
                    prev->op = '+';
                    expr = new node(-1);
                    ret.insert_after(prev, expr);
                    prev = expr;
                    expr = new node('*');
                    ret.insert_after(prev, expr);
                    prev = expr;
                }
                expr = new node(parseExpr(s, i, tbl));
            } else {
                expr = new node(c);
                ++i;
            }
            ret.insert_after(prev, expr);
            if (i == n)
                break;
            prev = expr;
        }
        startidx = i;

        return ret;
    }

    string normalizeTerm(string& s) {
        int i, j;
        int n;
        priority_queue<string, vector<string>, greater<string>> factors;
        string res;

        n = s.length();

        i = 0;
        for (;;) {
            for (j = i; j < n; j++) {
                if (s[j] == '*')
                    break;
            }
            factors.push(string(s, i, j - i));
            if (j == n)
                break;
            i = j + 1;
        }

        n = factors.size();

        res = factors.top();

        i = 1;
        for (;;) {
            if (i == n)
                break;
            factors.pop();
            res += '*' + factors.top();
            ++i;
        }

        return res;
    }

    node *add(node *opnd1, node *opnd2) {
        string s1, s2;

        s1 = normalizeTerm(opnd1->name);
        s2 = normalizeTerm(opnd2->name);

        return s1 == s2
               ? new node(opnd1->coeff + opnd2->coeff, string(opnd1->name))
               : nullptr;
    }

    node *sub(node *opnd1, node *opnd2) {
        string s1, s2;

        s1 = normalizeTerm(opnd1->name);
        s2 = normalizeTerm(opnd2->name);

        return s1 == s2
               ? new node(opnd1->coeff - opnd2->coeff, string(opnd1->name))
               : nullptr;
    }

    list_head mul(node *opnd1, node *opnd2) {
        int c1, c2;
        list_head res;
        list_head tmp1, tmp2;
        node *cur1, *cur2;
        node n1, n2;
        node *prev;
        node *tmp;

        if (opnd1->subexpr.head == nullptr && opnd2->subexpr.head == nullptr) {
            string s;

            if (opnd1->name.size() == 0) {
                if (opnd2->name.size() != 0)
                    s = opnd2->name;
            } else if (opnd2->name.size() == 0)
                s = opnd1->name;
            else
                s = opnd1->name + '*' + opnd2->name;
            s = normalizeTerm(s);
            res.insert_after(nullptr, new node(opnd1->coeff * opnd2->coeff, std::move(s)));
            return res;
        }

        if (opnd1->subexpr.head == nullptr) {
            n1 = *opnd1;
            tmp1.insert_after(nullptr, &n1);
            opnd1 = static_cast<node *>(tmp1.head);
        } else
            opnd1 = static_cast<node *>(opnd1->subexpr.head);
        if (opnd2->subexpr.head == nullptr) {
            n2 = *opnd2;
            tmp2.insert_after(nullptr, &n2);
            opnd2 = static_cast<node *>(tmp2.head);
        } else
            opnd2 = static_cast<node *>(opnd2->subexpr.head);

        prev = nullptr;
        for (cur1 = opnd1; cur1 != nullptr; cur1 = static_cast<node *>(cur1->next)) {
            if (cur1->op != 0)
                continue;
            c1 = cur1->coeff;
            if (cur1->prev != nullptr && static_cast<node *>(cur1->prev)->op == '-')
                c1 = -c1;
            cur2 = opnd2;
            for (;;) {
                int coeff;

                if (cur2->op == 0) {
                    if (prev != nullptr) {
                        tmp = new node('+');
                        res.insert_after(prev, tmp);
                        prev = tmp;
                    }
                    c2 = cur2->coeff;
                    if (cur2->prev != nullptr && static_cast<node *>(cur2->prev)->op == '-')
                        c2 = -c2;
                    coeff = c1 * c2;
                    if (cur1->name.size() == 0) {
                        tmp = cur2->name.size() == 0
                              ? new node(coeff)
                              : new node(coeff, string(cur2->name));
                    } else if (cur2->name.size() == 0)
                        tmp = new node(coeff, string(cur1->name));
                    else
                        tmp = new node(coeff, cur1->name + '*' + cur2->name);
                    tmp->name = normalizeTerm(tmp->name);
                    res.insert_after(prev, tmp);
                    prev = tmp;
                }
                cur2 = static_cast<node *>(cur2->next);
                if (cur2 == nullptr)
                    break;
            }
        }

        return res;
    }

    list_head evalExpr(list_head& ls) {
        char op;
        entry_cmp cmp;
        int i, n;
        list_head newls;
        node *cur;
        node *prev1, *prev2;
        node *ret;
        node *tmp;
        node_cmp ncmp;
        priority_queue<entry *, vector<entry *>, entry_cmp> pq1;
        priority_queue<entry *, vector<entry *>, node_cmp> pq2;

        for (cur = static_cast<node *>(ls.head);
             cur != nullptr;
             cur = static_cast<node *>(cur->next)) {
            if (cur->subexpr.head != nullptr) {
                newls = evalExpr(cur->subexpr);
                if (newls.head->next == nullptr) {
                    ls.insert_after(cur->prev, newls.head);
                    ls.remove(cur, cur);
                } else
                    cur->subexpr = newls;
            }
        }

        for (cur = static_cast<node *>(ls.head);
             cur != nullptr;
             cur = static_cast<node *>(cur->next)) {
            if (cur->op == '*') {
                newls = mul(static_cast<node *>(cur->prev), static_cast<node *>(cur->next));
                if (newls.head->next == nullptr)
                    ls.insert_after(cur->prev->prev, newls.head);
                else if (cur->next->next == nullptr || static_cast<node *>(cur->next->next)->op != '*') {
                    newls = evalExpr(newls);
                    ls.insert_after(cur->prev->prev, newls.head, newls.tail);
                } else {
                    tmp = new node(std::move(newls));
                    ls.insert_after(cur->prev->prev, tmp);
                }
                ls.remove(cur->prev, cur->next);
            }
        }

        for (cur = static_cast<node *>(ls.head);
             cur != nullptr;
             cur = static_cast<node *>(cur->next)) {
            if (cur->subexpr.head != nullptr) {
                if (cur->subexpr.head->next == nullptr)
                    ls.insert_after(cur->prev, cur->subexpr.head);
                else
                    ls.insert_after(cur->prev, cur->subexpr.head, cur->subexpr.tail);
                ls.remove(cur, cur);
            }
        }

        cmp.dir = 1;
        pq1 = priority_queue<entry *, vector<entry *>, entry_cmp>(cmp);

        op = 0;
        for (cur = static_cast<node *>(ls.head);
             cur != nullptr;
             cur = static_cast<node *>(cur->next)) {
            if (cur->op == 0)
                pq1.push(new entry(cur->coeff, &cur->name, op, -1, cur->subexpr));
            else
                op = cur->op;
        }

        n = pq1.size();

        ls.head = nullptr;

        tmp = nullptr;
        for (i = 0; i < n; i++) {
            entry *ent;
            node *cur;

            ent = pq1.top();
            pq1.pop();

            if (tmp != nullptr) {
                cur = new node(ent->op ? ent->op : '+');
                ls.insert_after(tmp, cur);
                tmp = cur;
            } else if (ent->op == '-')
                ent->coeff *= -1;

            cur = new node(ent->coeff);
            cur->name = ent->name;
            cur->subexpr = ent->subexpr;
            ls.insert_after(tmp, cur);
            tmp = cur;
        }

        for (cur = static_cast<node *>(ls.head);
             cur != nullptr;
             cur = static_cast<node *>(cur->next)) {
            if (cur->op == '*') {
                newls = mul(static_cast<node *>(cur->prev), static_cast<node *>(cur->next));
                if (newls.head->next == nullptr)
                    ls.insert_after(cur->prev->prev, newls.head->next);
                else {
                    newls = evalExpr(newls);
                    ls.insert_after(cur->prev->prev, newls.head, newls.tail);
                }
                ls.remove(cur->prev, cur->next);
            }
        }

        i = 0;
        for (cur = static_cast<node *>(ls.head);
             cur != nullptr;
             cur = static_cast<node *>(cur->next)) {
            if (cur->op == '+') {
                tmp = add(static_cast<node *>(cur->prev), static_cast<node *>(cur->next));
                if (tmp != nullptr) {
                    ls.insert_after(cur->prev->prev, tmp);
                    ls.remove(cur->prev, cur->next);
                }
            } else if (cur->op == '-') {
                tmp = sub(static_cast<node *>(cur->prev), static_cast<node *>(cur->next));
                if (tmp != nullptr) {
                    ls.insert_after(cur->prev->prev, tmp);
                    ls.remove(cur->prev, cur->next);
                }
            }
            ++i;
        }

        pq2 = priority_queue<entry *, vector<entry *>, node_cmp>(ncmp);

        op = 0;
        for (cur = static_cast<node *>(ls.head);
             cur != nullptr;
             cur = static_cast<node *>(cur->next)) {
            if (cur->op == 0) {
                cur->setDegree();
                pq2.push(new entry(cur->coeff, &cur->name, op, cur->degree, cur->subexpr));
            } else
                op = cur->op;
        }

        n = pq2.size();

        ls.head = nullptr;

        tmp = nullptr;
        for (i = 0; i < n; i++) {
            entry *ent;
            node *cur;

            ent = pq2.top();
            pq2.pop();

            if (tmp != nullptr) {
                cur = new node(ent->op ? ent->op : '+');
                ls.insert_after(tmp, cur);
                tmp = cur;
            } else if (ent->op == '-')
                ent->coeff *= -1;

            cur = new node(ent->coeff);
            cur->name = ent->name;
            cur->subexpr = ent->subexpr;
            ls.insert_after(tmp, cur);
            tmp = cur;
        }

        return ls;
    }

    void _dumpExpr(node *expr) {
        node *cur;

        for (cur = expr; cur != nullptr; cur = static_cast<node *>(cur->next)) {
            if (cur->op == 0)
                cout << cur->coeff;
            if (cur->name.size() > 0) {
                if (cur->coeff != 0)
                    cout << '*';
                cout << cur->name;
            } else if (cur->op != 0)
                cout << cur->op;
            else if (cur->subexpr.head != nullptr) {
                cout << '(';
                _dumpExpr(static_cast<node *>(cur->subexpr.head));
                cout << ')';
            }
        }
    }

    void dumpExpr(node *expr) {
        _dumpExpr(expr);
        cout << endl;
    }

    vector<string> cvtExpr(node *expr) {
        bool neg;
        node *cur;
        vector<string> res;

        neg = false;
        for (cur = expr; cur != nullptr; cur = static_cast<node *>(cur->next)) {
            string s;

            if (cur->op == '+') {
                neg = false;
                continue;
            }
            if (cur->op == '-') {
                neg = true;
                continue;
            }
            if (cur->coeff == 0)
                continue;
            s += to_string(neg ? -cur->coeff : cur->coeff);
            if (cur->name.size() > 0) {
                if (cur->coeff != 0)
                    s += '*';
                s += cur->name;
            }
            if (s.length() > 0)
                res.push_back(s);
        }

        return res;
    }

public:
    vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
        evalmap tbl;
        int i, n;
        list_head ls;
        node *cur, *expr;

        n = evalvars.size();

        for (i = 0; i < n; i++)
            tbl[&evalvars[i]] = evalints[i];

        i = 0;
        ls = parseExpr(expression, i, tbl);

        ls = evalExpr(ls);

        return cvtExpr(static_cast<node *>(ls.head));
    }
};
23000