andyli

题解 洛谷 P4711 【「化学」相对分子质量】
这题只要按照题目说的做就可以了(用递归会比较好)代码如下:#include <iostream> #i...
扫描右侧二维码阅读全文
05
2018/07

题解 洛谷 P4711 【「化学」相对分子质量】

这题只要按照题目说的做就可以了(用递归会比较好)
代码如下:

#include <iostream>
#include <string>
#include <cctype>
#include <map>
using namespace std;

map<string, double> m;
void init()
{
    m["H"] = 1;
    m["C"] = 12;
    m["N"] = 14;
    m["O"] = 16;
    m["F"] = 19;
    m["Na"] = 23;
    m["Mg"] = 24;
    m["Al"] = 27;
    m["Si"] = 28;
    m["P"] = 31;
    m["S"] = 32;
    m["Cl"] = 35.5;
    m["K"] = 39;
    m["Ca"] = 40;
    m["Mn"] = 55;
    m["Fe"] = 56;
    m["Cu"] = 64;
    m["Zn"] = 65;
    m["Ag"] = 108;
    m["I"] = 127;
    m["Ba"] = 137;
    m["Hf"] = 178.5;
    m["Pt"] = 195;
    m["Au"] = 197;
    m["Hg"] = 201;
}

double f(string str)
{
    if (m.count(str))
        return m[str];
    size_t pos = str.find('~');
    if (pos != string::npos)
        return f(str.substr(0, pos)) + f(str.substr(pos + 1));
    if (isupper(str[0]))
    {
        int t = 1, flag = bool(islower(str[1])), ok = 0;
        if (str[flag + 1] == '_')
            t = stoi(str.substr(flag + 3, (pos = str.find('}')) - flag - 3)), ok = 1;
        return t * m[str.substr(0, flag + 1)] + f(str.substr(ok ? (pos + 1) : (flag + 1)));
    }
    int t = 0, i = 0;
    while (isdigit(str[i]))
        t = t * 10 + str[i++] - '0';
    if (t > 0)
        return t * f(str.substr(i));
    if (str[0] == '(')
    {
        int cnt = 1, len = str.length();
        for (i = 1; i < len; i++)
        {
            if (str[i] == '(')
                cnt++;
            else if (str[i] == ')')
                cnt--;
            if (cnt == 0)
                break;
        }
        t = 1;
        if(str[i + 1] == '_')
            t = stoi(str.substr(i + 3, (pos = str.find(i + 3, '}')) - i - 3)), cnt = 1;
        return t * f(str.substr(1, i - 1)) + f(str.substr(cnt ? (i + 1) : (pos + 1)));
    }
    return 0;
}

int main()
{
    init();
    string str;
    cin >> str;
    cout << f(str) << endl;
    return 0;
}

代码可能有点乱,但只要认真一看就会发现其实这题很简单。
大家有没有注意到代码中的f函数中,用到了一个函数stoi,这个函数是C++11新增的,可以把字符串变成整数。

Last modification:June 25th, 2019 at 11:05 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment