CSP(三)

#include <bits/stdc++.h>
using namespace std;

unordered_map<string, int> parseFormulaEx(string::iterator s, string::iterator e) {
    unordered_map<string, int> cnt;
    // 计算系数
    int coef = 0;
    while (isdigit(*s)) {
        coef = coef * 10 + *s - '0';
        ++s;
    }
    coef = max(coef, 1);

    while (s != e) {
        unordered_map<string, int> temp;
        if (*s == '(') { // 找到匹配的')'
            auto p = s + 1;
            int cnt = 1;
            while (cnt != 0) {
                if (*p == '(')
                    ++cnt;
                else if (*p == ')')
                    --cnt;
                ++p;
            }
            temp = parseFormulaEx(s + 1, p - 1); // 去掉括号,递归
            s = p;
        } else {
            string element(1, *s);
            if (s + 1 != e && islower(*(s + 1))) {
                element.append(1, *(s + 1));
                ++s;
            }
            temp[element] = 1;
            ++s;
        }

        // 计算下标
        int subscript = 0;
        while (s != e && isdigit(*s)) {
            subscript = subscript * 10 + *s - '0';
            ++s;
        }
        subscript = max(subscript, 1);

        // 计入总量
        for (const auto& ele: temp) {
            cnt[ele.first] += subscript * ele.second;
        }
    }
    for (auto& ele: cnt) ele.second *= coef;
    return cnt;
}

unordered_map<string, int> parseExpr(string::iterator s, string::iterator e) {
    //cout << string(s, e) << endl;
    unordered_map<string, int> cnt;
    while (s != e) {
        auto p = find(s, e, '+');
        auto temp = parseFormulaEx(s, p);
        for (const auto& ele: temp) cnt[ele.first] += ele.second;
        if (p != e) ++p; // 跳过'+'
        s = p;
    }
    //for (const auto& ele: cnt) cout << ele.first << "\t" << ele.second << endl; cout << endl;
    return cnt;
}

bool isValid(string& equation) {
    auto eq = find(equation.begin(), equation.end(), '=');
    auto left = parseExpr(equation.begin(), eq);
    auto right = parseExpr(eq + 1, equation.end());
    if (left.size() != right.size()) return false;
    for (const auto& ele: left) {
        if (!right.count(ele.first) || right[ele.first] != ele.second) return false;
    }
    return true;
}

int main() {
    int n;
    cin >> n;
    string equation;
    while (n--) {
        cin >> equation;
        cout << (isValid(equation) ? "Y" : "N") << endl;
    }
    return 0;
}


太难了,我吐了、
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值