CCF CSP 化学方程式

6 篇文章 0 订阅

模拟题 + 简单的递归

#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");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值