反思
讲真的昨晚这道题有点把我写傻了,真.大模拟…写到后面真有点写不下去了,反正写了大概有两个小时吧…感觉CCF看中的根本就不是什么算法能力好么?感觉完全是编码能力的考察…
数字 | 右括号 | 左括号 | 加号 | 大写字母 | 等号 |
---|---|---|---|---|---|
前一个为右括号 | 放入序列中 | 放入序列中 | 整个化学式系数结算 | 下一个是小写字母 | 总结各元素 |
前一个是元素名 | 下一个非小写字母 | ||||
前一个是加号 | |||||
为该化学式的起始 |
以上便是大部分情况,细节请自行完善
Code(70分)
#include<bits/stdc++.h>
using namespace std;
int n, j = 0, flag = 0, p = 0;
string s="";
map<string, int>l, r;
class node
{
public:
node(){
numm = 1;
}
node(int a, string b) :numm(a), str(b) {}
int numm;
string str;
};
vector<node> a;
bool judge(map<string, int>& left, map<string, int>& right)//判断两个map是否相同
{
if (left.size() != right.size()) return false;
for (map<string, int>::iterator it = left.begin(); it != left.end(); ++it)
if (right[it->first] != it->second)
return false;
return true;
}
int count(int dis)//计数
{
int sum = 0;
while (isdigit(s[dis]))
{
sum = sum * 10 + s[dis] - '0';
dis++;
}
j = dis;
return sum;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
string tr;
cin >> tr;//原式
s = "";
s += tr;
s = tr + '+';
j = 0;
p = 0;
while (j < s.size())
{
if (isdigit(s[j]))//数字
{
if (j == 0 || s[j - 1] == '+' || s[j - 1] == '=')//整个化学式的常数
flag = 1;
int num = count(j);
if (flag == 1)
flag = num;
else if (j != 0 && a[a.size() - 1].str == ")")//前一个是右括号
{
a[a.size() - 1].str = "*";
int temp = a.size();
while (a[--temp].str != "(")
{
if (a[temp].str == "*")
continue;
else
a[temp].numm = num * a[temp].numm;
}
if (a[temp].str == "(")
a[temp].str = "*";
}
else
{
int t = a.size() - 1;
if (a[t].str == "*")
t--;
a[t].numm = num * a[t].numm;
}
}
else if (s[j] == '(')
{
node temp(1, "(");
a.push_back(temp);
j++;
}
else if (s[j] == ')')
{
if (j < tr.size() - 1 && !isdigit(s[j + 1]))
{
s[j] = '*';
int temp = a.size();
while (a[--temp].str != "(");
a[temp].str = "*";
node t(1, "*");
a.push_back(t);
}
else
{
node temp(1, ")");
a.push_back(temp);
}
j++;
}
else if (s[j] == '+' || s[j] == '=')
{
if (flag > 1)
{
int temp = a.size() - 1;
while (temp >= p)
{
if (a[temp].str != "*")
a[temp].numm = a[temp].numm * flag;
temp--;
}
}
if (s[j] == '=')
{
int temp = a.size();
while (--temp >= 0)
if (a[temp].str != "*")
l[a[temp].str] += a[temp].numm;
a.clear();
}
j++;
p = a.size();
flag = 0;
}
else if (isupper(s[j]))//大写字母
{
if (j < s.size() - 1 && islower(s[j + 1]))
{
string temp = "";
temp += s[j];
temp += s[j + 1];
node t(1, temp);
a.push_back(t);
j += 2;
}
else
{
string temp = "";
temp += s[j];
node t(1, temp);
a.push_back(t);
j++;
}
}
if (j >= s.size())
{
int temp = a.size();
while (--temp>=0)
if (a[temp].str != "*")
r[a[temp].str] += a[temp].numm;
a.clear();
}
}
if (judge(l, r))
cout << "Y" << endl;
else
cout << "N" << endl;
l.clear();
r.clear();
}
return 0;
}