【UVA – 1586】Molar mass【紫书】

【UVA – 1586】Molar mass【紫书】

问题链接:https://vjudge.net/problem/UVA-1586

udebug数据链接:https://www.udebug.com/UVa/1586

备注:推测测试数据中有的行末尾存在多余空格,所以对于每一个读入的字符,要明确判断其是否是字母或数字。

Solution 1 – 逐行处理的思路,每次读取一行到数组中,之后处理读入的这一行数据:

#include <iostream>
#include <cctype>
#include <map>

using namespace std;

const int LIM = 81;
char data[LIM];

int main(void) {
    int t;
    scanf("%d", &t);
    fgets(data, LIM, stdin);
    map<char, double> m;
    m['C'] = 12.01;
    m['H'] = 1.008;
    m['O'] = 16.00;
    m['N'] = 14.01;
    while (t--) {
        fgets(data, LIM, stdin);
        double ans = 0;
        int num = 0;
        char ch = data[0];
        for (int i = 1; data[i] != '\n'; i++) {
            if (isalpha(data[i])) {
                if (!num) num = 1;
                ans += num * m[ch];
                ch = data[i];
                num = 0;
            } else if (isdigit(data[i])){
                num = num * 10 + data[i] - '0';
            }
        }
        if (!num) num = 1;
        ans += m[ch] * num;       //add the last element of each line
        printf("%.3lf\n", ans);
    }
    return 0;
}

 

Solution 2 – 逐个字符处理的思路:

#include <iostream>
#include <map>
#include <cctype>

using namespace std;

int main(void) {
    map<char, double> m;
    m['C'] = 12.01;
    m['H'] = 1.008;
    m['O'] = 16;
    m['N'] = 14.01;
    m['.'] = 0;
    int n;
    scanf("%d", &n);
    getchar();
    char ch, pre;
    int num;
    double ans;
    while (n--) {
        ans = 0;
        num = -1;
        while (ch = getchar()) {
            if (ch == EOF || ch == '\n') {
                if (!num) num = 1;
                ans += num * m[pre];
                pre = '.';
                printf("%.3f\n", ans);
                break;
            } else if (isalpha(ch)) {
                if (!num) num = 1;
                ans += num * m[pre];
                pre = ch;
                num = 0;
            } else if (isdigit(ch)) {
                num = num * 10 + ch - '0';
            }
        }
    }
    return 0;
}

 

相关阅读:

《算法竞赛入门经典》(紫书)全AC代码