首页 > 代码库 > UVA 1586 - Molar mass

UVA 1586 - Molar mass

#include <cstdio>
#include <cstring>
int key[5];
double value[5]={0,12.01,1.008,14.01,16.00};
int T;
int num=0,p=0,flag=0;
int check(char ch)
{
    switch(ch)
    {
    case 'C':
        return 1;
    case 'H':
        return 2;
    case 'N':
        return 3;
    case 'O':
        return 4;
    }
}
int main()
{
    int len,i;
    scanf("%d",&T);
    char str[100];
    while(T--)
    {
        scanf("%s",str);
        memset(key,0,sizeof(key));
        num=0,p=0,flag=0;
        len = strlen(str);
        for(i=0; i<len;++i)
        {
            if(str[i]>='C' && str[i]<='O')
            {
                if(flag)
                {
                    if(key[p] >0)
                        key[p] += num;
                    else
                        key[p] = num;
                    flag=0; num=0;
                }
                p = check(str[i]);
                if(i==len-1 || (str[i+1]>='C' && str[i+1]<='O'))
                   ++key[p];
            }
            else
            {
                flag=1;
                num = num*10+(str[i]-'0');
                if(i == len-1)
                {
                    if(key[p] >0)
                        key[p] += num;
                    else
                        key[p] = num;
                }
            }
        }

        double result=0;
        for(i=1;i<=4;++i)
        {
            result += key[i]*value[i];
        }
        printf("%.3lf\n",result);
    }
    return 0;
}


题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=830&page=show_problem&problem=4461


UVA 1586 - Molar mass