原题:
An organic compound is any member of a large class of chemical compounds whose molecules contain carbon. The molar mass of an organic compound is the mass of one mole of the organic compound. The molar mass of an organic compound can be computed from the standard atomic weights of the elements. When an organic compound is given as a molecular formula, Dr. CHON wants to find its molar mass. A molecular formula, such as C 3 H 4 O 3 , identifies each constituent element by its chemical symbol and indicates the number of atoms of each element found in each discrete molecule of that compound. If a molecule contains more than one atom of a particular element, this quantity is indicated using a subscript after the chemical symbol. In this problem, we assume that the molecular formula is represented by only four elements, ‘C’ (Carbon), ‘H’ (Hydrogen), ‘O’ (Oxygen), and ‘N’ (Nitrogen) without parentheses. The following table shows that the standard atomic weights for ‘C’, ‘H’, ‘O’, and ‘N’.
中文:
给你一个化学式,现在问你这个化学式的分子量是多少。元素只有碳氢氧氮。
#include <bits/stdc++.h>
using namespace std;
bool judge(char c)
{
if(c=='C'||c=='H'||c=='O'||c=='N')
return true;
return false;
}
double solve(char c)
{
if(c=='C')
return 12.01;
if(c=='H')
return 1.008;
if(c=='O')
return 16.00;
return 14.01;
}
int main()
{
ios::sync_with_stdio(false);
int n;
string s;
cin>>n;
while(n--)
{
cin>>s;
double ans=0;
int i=0;
if(s.size()==1)
{
cout<<fixed<<setprecision(3)<<solve(s[0])<<endl;
continue;
}
while(i<s.size())
{
if(judge(s[i]))
{
if(i+1<s.size())
{
int j=i+1;
if(judge(s[j]))
{
ans+=solve(s[i]);
i++;
}
else
{
string tmp="";
while(j<s.size()&& !judge(s[j]))
{
tmp+=s[j];
j++;
}
double num=stod(tmp);
ans+=(solve(s[i])*num);
i=j;
}
}
else
{
ans+=solve(s[i]);
break;
}
}
}
cout<<fixed<<setprecision(3)<<ans<<endl;
}
return 0;
}
解答:
普通的模拟题,练练代码还凑合