CCF 化学方程式

#include <iostream>
#include <cstring>
#include <map>
#include <algorithm>

using namespace std;
string equa;
int match(int i)
{
    int c = 0;
    while(i < equa.size())
    {
        if(equa[i] == '(') c ++;
        else if(equa[i] == ')') c --;
        if(c == 0) return i;
        i ++;
    }
}
void term(map<string,int> &mp,int coef,int l,int r) // Cl23
{
    int pos = r;
    while(pos >= l && isdigit(equa[pos])) pos --;
    int coef1 = 0;
    for(int k = pos + 1; k <= r; ++k) coef1 = coef1 * 10 + equa[k] - '0';
    if(!coef1) coef1 ++;
    //l - pos;
    mp[equa.substr(l, pos - l + 1)] += coef * coef1;
}
void word(map<string,int> &mp,int coef,int l,int r) // NaCl2(Au(CN)2)5 * coef
{

    for(int i = l; i <= r;)
    {
        if(equa[i] == '(')
        {
            int q = match(i);
            int j = q + 1;
            int coef1 = 1;
            word(mp,coef * coef1,i + 1, q - 1);
            i = j;
        }
        else
        {
            int q = i + 1;
            while(q <= r && isdigit(equa[q]) || islower(equa[q])) q ++; // Nl123
            term(mp,coef,i,q - 1);
            i = q;
        }
    }

}
void word_k(map<string,int> &mp,int l,int r) // 4Na(Au(CN)2)5
{
    int coef = 0;
    while(isdigit(equa[l])) coef = coef * 10 + equa[l ++] - '0';
    if(!coef) coef ++;
    word(mp,coef,l,r);
}
map<string,int> words(int l,int r)  // ... + ....
{
    map<string,int> mp;
    int pre = l;
    for(int i = l; i <= r; ++i)
    {
        if(equa[i] == '+')
        {
            word_k(mp,pre, i - 1);
            pre = i + 1; 
        }
    }
    word_k(mp,pre,r);
    return mp;
}
int main()
{
    int T; cin >> T;
    while(T --)
    {
        cin >> equa;
        int e = find(equa.begin(),equa.end(),'=') - equa.begin();
        int ans = words(0,e - 1) == words(e + 1,equa.size() - 1);
        if(ans) puts("Y");
        else puts("N");
    }
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
转发
1 收藏 评论
分享
牛客网
牛客企业服务