201912-3 化学方程式

试题编号: 201912-3
试题名称: 化学方程式
时间限制: 1.0s
内存限制: 512.0MB
在这里插入图片描述在这里插入图片描述在这里插入图片描述
前四个测试点还是很好写的,不过加入小写字母要注意Cu+As=Cs+Au这种情况,不能只是判断字符种类的数目是否相同

#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=30;
int pos;
int cnt[N],cntd[N][N];
int num(string &s)
{
	int t=0;
	while(isdigit(s[pos]))
	{
		t=t*10+(s[pos]-'0');
		pos++;
	}
	return t;
}
void count(string &s,int d)
{
	int len=s.size();
	pos=0;
	if(isdigit(s[0])) d*=num(s);
	while(pos<len)
	{
		if(isdigit(s[pos]))
		{
			int post=pos-1;
			int dd=num(s);
			if(islower(s[post]))
			{
				cntd[s[post-1]-'A'][s[post]-'a']+=d*(dd-1);
			}
			else
			{
				cnt[s[post]-'A']+=d*(dd-1);
			}
		}
		else if(islower(s[pos]))
		{
			cnt[s[pos-1]-'A']-=d;
			cntd[s[pos-1]-'A'][s[pos]-'a']+=d;
			pos++;
		}
		else if(isupper(s[pos]))
		{
			cnt[s[pos]-'A']+=d;
			pos++;
		}
		else if(s[pos]=='(')
		{
			int posr=s.find(')',pos),tt,dd=1;
			string sub=s.substr(pos+1,posr-pos-1);
			if(isdigit(s[posr+1]))
			{
				pos=posr+1;
				dd=num(s);
				tt=pos;
			}
			else tt=posr+1;
			count(sub,dd*d);
			pos=tt;
		}
	}
}
void sep(string &s,int d)
{
	int pos1=0,pos2=s.find('+');
	string sub;
	while(pos2!=-1)
	{
		sub=s.substr(pos1,pos2-pos1);
		count(sub,d);
		pos1=pos2+1;
		pos2=s.find('+',pos1);
	}
	sub=s.substr(pos1);
	count(sub,d);
}
int main()
{
	int n;
	cin>>n;
	while(n--)
	{
		memset(cnt,0,sizeof cnt);
		memset(cntd,0,sizeof cntd);
		string s,sl,sr;
		cin>>s;
		int pos=s.find('=');
		sl=s.substr(0,pos);
		sr=s.substr(pos+1);
		sep(sl,1);
		sep(sr,-1);
		bool flag=true;
		for(int i=0;i<N;i++)
		{
			if(cnt[i]!=0)
			{
				flag=false;
				break;
			}
		}
		if(flag)
		{
			for(int i=0;i<N;i++)
			for(int j=0;j<N;j++)
			{
				if(cntd[i][j]!=0)
				{
					flag=false;
					break;
				}
			}
			if(flag) cout<<"Y"<<endl;
			else cout<<"N"<<endl;
		}
		else cout<<"N"<<endl;
	}
	return 0;
}
/*
10
H2+O2=H2O
2H2+O2=2H2O
H2+2Cl=2NaCl
H2+2Cl=2HCl
CH4+2O2=CO2+2H2O
CaCl2+2AgNO3=Ca(NO3)2+2AgCl
3Ba(OH)2+2H3PO4=6H2O+Ba3(PO4)2
3Ba(OH)2+2H3PO4=Ba3(PO4)2+6H2O
4Zn+10HNO3=4Zn(NO3)2+NH4NO3+3H2O
Cu+As=Cs+Au
*/

个人觉得圆括号的嵌套性价比是在不高,所以就没考虑嵌套情况,代码只有80分。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值