CCF CSP 化学方程式

模拟题 + 简单的递归

#include <bits/stdc++.h>
using namespace std;
int find_ep(string &s)
{
	for(int i = 0; i < s.size(); ++ i)
		if(s[i] == '=') return i;
    return -1;
}
void work_2(string word, map<string,int> &res,int K)
{
    int i = 0, k = 0;
    while(i < word.size() && isdigit(word[i])) k = k * 10 + word[i ++] - '0';
    if(!k) k = 1;
    while(i < word.size())
    {
        if(word[i] == '(')
        {
            stack<char> stk;
            stk.push(word[i ++]);
            int l = i, r = i;
            while(stk.size())
            {
                if(word[i] == '(') stk.push(word[i ++]);
                else if(word[i] == ')') 
                {
                    stk.pop();
                    i ++;
                }
                else i ++;
                if(stk.empty())
                {
                    r = i - 2;
                    int cnt = 0;
                    while(i < word.size() && isdigit(word[i])) cnt = cnt * 10 + word[i ++] - '0';
                    if(!cnt) cnt = 1;
                    work_2(word.substr(l, r - l + 1), res, cnt * k * K);
                }
            }
        }
        else
        {
            int cnt = 0;
            string alp = "";
            alp += word[i ++];
            if(i < word.size() && 'a' <= word[i] && word[i] <= 'z') alp += word[i ++];
            while(i < word.size() && isdigit(word[i])) cnt = cnt * 10 + word[i ++] - '0';
            if(!cnt) cnt = 1;
            res[alp] += k * cnt * K;
        }
        
    }
}
void work_1(string s, map<string, int> &res)
{
    string word = "";
    for(int i = 0; i <= s.size(); ++ i)
    {
        if(i == s.size() || s[i] == '+')
        {
            work_2(word, res, 1);
            word = "";
        }
        else word += s[i];
    }
}
bool judge(string &s)
{
	int ep = find_ep(s);
	map<string, int> l, r;
 	work_1(s.substr(0, ep), l);
 	work_1(s.substr(ep + 1), r);
 	return l == r;
}
int main()
{
	string s;
	int n; cin >> n;
	while(n --)
	{
		cin >> s;
		if(judge(s)) puts("Y");
		else puts("N");
	}
}

 

上一篇:战略游戏[SDOI2018]


下一篇:库存账龄报表开发总结——Sqlserver LAG()的使用