fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. int cal(string fomulas){
  5. unordered_map <char, int> atomic {
  6. {'H',1},
  7. {'C',12},
  8. {'N',14},
  9. {'O',16}
  10. };
  11. regex molecule ("([HCNO])(\\d*)");
  12. smatch match;
  13. int weight = 0;
  14. string remain = fomulas;
  15. while (regex_search (remain, match, molecule)){
  16. char element = match[1].str()[0];
  17. int count = 1;
  18. if (!match[2].str().empty()) count = stoi (match[2].str());
  19. weight += atomic[element] * count;
  20. remain = match.suffix().str();
  21. }
  22. return weight;
  23. }
  24. int main() {
  25. ios_base::sync_with_stdio(false);
  26. cin.tie(NULL);
  27. string fomulas;
  28. cin >> fomulas;
  29. cout << cal(fomulas);
  30. return 0;
  31. }
Success #stdin #stdout 0.01s 5548KB
stdin
C2H4
stdout
28