XM27. 计算原子的个数
描述
给出一个字符串格式的化学分子式,计算原子的个数输入描述
一行,一个字符串表示输入的分子式输出描述
按要求输出答案示例1
输入:
H2O
输出:
H2O
示例2
输入:
Mg(OH)2
输出:
H2MgO2
示例3
输入:
K4(ON(SO3)2)2
输出:
K4N2O14S4
C++14 解法, 执行用时: 2ms, 内存消耗: 404KB, 提交时间: 2020-09-03
#include <iostream> #include <map> #include <string> #include <vector> #include <stdlib.h> using namespace std; typedef map<string, int> mst; string hxs; int posi = 0; int len; mst ele; int getdigit() { int num = 0; while ('0' <= hxs[posi] && hxs[posi] <= '9') { num = num * 10 + hxs[posi] - '0'; if (posi<len) posi++; } return num; } void mapAdd(mst& map1, mst& map2) { for (auto m : map2) { map1[m.first] += m.second; } } void solve(mst &ans) { mst mp; string pr; while (posi < len) { if (hxs[posi] == ')') { if (pr != "") { mp[pr]++; } posi++; int mlp = getdigit(); mst::iterator p = mp.begin(); while(p!=mp.end()) { p->second = p->second * mlp; p++; } mapAdd(ans, mp); return; } if (hxs[posi] == '(') { if (pr != "") { mp[pr]++; pr = ""; } posi++; solve(mp); } if ('A' <= hxs[posi] && hxs[posi] <= 'Z') { if (pr!="") { mp[pr]++; pr = ""; pr.push_back(hxs[posi]); } else { pr.push_back(hxs[posi]); } posi++; } if ('a' <= hxs[posi] && hxs[posi] <= 'z') { pr.push_back(hxs[posi]); posi++; } if ('0' <= hxs[posi] && hxs[posi] <= '9') { int mlp = getdigit(); mp[pr] = mp[pr] + mlp; pr = ""; } if (hxs[posi] == '\0') { if (pr != "") { mp[pr]++; } } } mapAdd(ele, mp); return; } int main() { cin >> hxs; len = hxs.length(); mst m; solve(m); for (auto rslt : ele) { if (rslt.second > 1) cout << rslt.first << rslt.second; else cout << rslt.first; } cout << endl; return 0; }
C++ 解法, 执行用时: 2ms, 内存消耗: 488KB, 提交时间: 2019-08-21
#include <iostream> #include <vector> #include <string> #include <deque> #include <map> using namespace std; int main() { int mtipule=1; deque<int> muti1; int kuohao=0,geshu=0; vector<string> elem; vector<int> elem_geshu; string s,temp_int="",temp_elem=""; cin>>s; for(int i=s.size()-1;i>=0;i--) { if(s[i]>='0'&&s[i]<='9') temp_int=s[i]+temp_int; else { if(temp_int!="") { muti1.push_front(atoi(temp_int.c_str())); mtipule=mtipule*atoi(temp_int.c_str()); geshu++; temp_int=""; } if(s[i]>='a'&&s[i]<='z') { temp_elem=s[i]+temp_elem; } if(s[i]>='A'&&s[i]<='Z') { elem.push_back(s[i]+temp_elem); elem_geshu.push_back(mtipule); //cout<<s[i]+temp_elem<<" "<<mtipule<<endl; if(geshu>kuohao) { if(mtipule!=1) { mtipule=mtipule/muti1.front(); muti1.pop_front(); } geshu--; } temp_elem=""; } else { if(s[i]==')') kuohao++; if(s[i]=='(') { if(mtipule!=1) { mtipule=mtipule/muti1.front(); muti1.pop_front(); } geshu--; kuohao--; } } } } map<string,int> m1; for(int i=0;i<elem.size();i++) { m1[elem[i]]=m1[elem[i]]+elem_geshu[i]; } map<string,int>::iterator iter; for(iter = m1.begin(); iter != m1.end(); iter++) { if(iter->second==1) cout<<iter->first; else cout<<iter->first<<iter->second; } cout<<endl; return 0; }