原题地址:点击打开链接
#include<stdio.h>
#include<string.h>
#include<stack>
#define MAX 1<<31-1
using namespace std;
int a[256];
int jisuan(int i,int b)
{
return a[i]*b;
}
int main()
{
int k,len,i,res,count;
char str[500];
a['N']=14;a['C']=12;a['O']=16;a['C'+'l'*2]=35;a['S']=32;a['H']=2;a['A'+'l'*2]=27;a['C'+'a'*2]=40;//为什么要乘2?,因为 'C'+'l'=='N'+'a',好吧。。
a['Z'+'n'*2]=65; a['N'+'a'*2]=23;
scanf("%d",&k);
while(k--)
{
res=0;
count=1;
stack<int>s;
scanf("%s",str);
len=strlen(str);
for(i=0;i<len;i++)
if(str[i]=='=')
break;
i++;
if(str[i]>='0'&&str[i]<='9')
count=str[i++]-'0';
while(str[i]!='+'&&str[i]!='\0')
{
if(str[i]>='A'&&str[i]<='Z'&&str[i+1]>='a'&&str[i+1]<='z')
{
if(str[i+2]>='0'&&str[i+2]<='9')
{
int res=jisuan(str[i+1]*2+str[i],str[i+2]-'0');
s.push(res);
i+=3;
}
else
{
s.push(a[str[i+1]*2+str[i]]);
i+=2;
}
}
else if(str[i]>='A'&&str[i]<='Z')
{
if(str[i+1]>='0'&&str[i+1]<='9')
{
int res=jisuan(str[i],str[i+1]-'0');
s.push(res);
i+=2;
}
else
{
s.push(a[str[i]]);
i+=1;
}
}
else if(str[i]=='(')
{
i++;
s.push(MAX);
}
else if(str[i]==')')
{
int sum=0;
while(s.top()!=MAX)
{
sum+=s.top();
s.pop();
}
s.pop();
i++;
if(str[i]>='0'&&str[i]<='9')
{
s.push(sum*(str[i]-'0'));
i++;
}
else
{
s.push(sum);
}
}
}
while(!s.empty())
{
res+=s.top();
s.pop();
}
if(res<10)
printf("0");
if(res<100)
printf("0");
if(res<1000)
printf("0");
printf("%d\n",res*count);
}
return 0;
}
本文介绍了一种使用 C 语言实现的化学式解析算法,能够处理包含括号和各种化学元素的复杂化学式,并通过栈来计算化学式的总质量。文章详细展示了如何定义化学元素的质量、读取输入、解析化学式中的元素及其数量,以及处理括号内的重复计算。
475

被折叠的 条评论
为什么被折叠?



