问题描述
p1586相关说明:本题为《算法竞赛入门经典(第2版)》习题 3-2
解法一:模拟
扫描字符串,遍历到元素所代表的字符时,先看看后面是数字还是字符:如果后面直接是其它元素的字符,直接表明当前元素的原子数为 1;如果后面是一串数字,则求得该元素的原子个数,计算其质量并累加到分子质量 res 中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <bits/stdc++.h> using namespace std; int main() { const map<char, float> TABLE = { {'C', 12.01}, {'H', 1.008}, {'O', 16.00}, {'N', 14.01}}; int t; cin >> t; while (t--) { string formula; cin >> formula; float res = 0; for (int i = 0; i < formula.length(); ++i) { char atomic = formula[i]; int cnt = 1; bool cnt_ommitted = true; while (i + 1 < formula.length() && isdigit(formula[i + 1])) { int digit = formula[++i] - '0'; cnt = cnt_ommitted ? digit : 10 * cnt + digit; cnt_ommitted = false; } res += TABLE.at(atomic) * cnt; } cout << fixed << setprecision(3) << res << endl; } return 0; } |
Python 代码会 Runtime Error, 没有花时间去找原因:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
TABLE = {'C': 12.01, 'H': 1.008, 'O': 16.00, 'N': 14.01} t = int(input()) for _ in range(t): formula = input() res = pos = 0 while pos < len(formula): atomic = formula[pos] cnt = 1 cnt_omitted = True while (pos + 1 < len(formula) and formula[pos + 1].isdigit()): pos += 1 digit = ord(formula[pos]) - ord('0') cnt = digit if cnt_omitted else 10 * cnt + digit cnt_omitted = False res += TABLE[atomic] * cnt pos += 1 print(f"{res:.3f}") |