很久之前写过的题,再写还是会出现一些问题,本来第一种写法
考虑传字符串进去,但涉及到str,所以超时了,然后就考虑传下标
进去处理,意外可以了。还是好菜啊。。。。。。
#include <bits/stdc++.h>
using namespace std;
vector<string> split(const string& s, char sp) {
stringstream ss (s);
string tmp;
vector<string> ret;
while (getline(ss,tmp,sp)) {
ret.push_back(tmp);
}
return ret;
}
int calcCoef(const string& str,int& pos) {
int num = 0;
while (pos < str.size() && isdigit(str[pos])) {
num = num * 10 + str[pos] - '0'; pos++;
}
return max(num, 1);
}
bool cmp(map<string,int>& l,map<string,int>& r){
if(l.size() != r.size()) return false;
for(auto& e:l){
if(e.second != r[e.first])
return false;
}
return true;
}
map<string,int> solve_str(const string& str,int& pos) {
map<string,int> ret;
while (pos < str.size()) {
if (str[pos] == '(') {
pos++;
auto tmp = solve_str(str,pos);
pos++;
int num = calcCoef(str,pos);
for (auto& pi : tmp) {
ret[pi.first] += num * pi.second;
}
} else if (str[pos] >= 'a' && str[pos] <= 'z') {
string e; e.push_back(str[pos - 1]);
e.push_back(str[pos]);
pos++;
int num = calcCoef(str,pos);
ret[e] += num;
} else if (str[pos] >= 'A' && str[pos] <= 'Z') {
string e; e.push_back(str[pos]);
pos++;
if (pos < str.size() && str[pos] >= 'a' && str[pos] <= 'z') {
e.push_back(str[pos]); pos++;
}
int num = calcCoef(str,pos);
ret[e] += num;
} else if (str[pos] == ')') {return ret;}
}
return ret;
}
map<string,int> resolve(const vector<string>& exprs) {
map<string,int>ret;
for (auto& expr : exprs) {
int pos = 0;
int coef = 0;
while (isdigit(expr[pos])) {
coef = coef * 10 + expr[pos] - '0';
pos++;
}
coef = max(coef,1);
int ps = 0;
map<string,int> tmp = solve_str(expr.substr(pos),ps);
for (auto& pi: tmp) {
ret[pi.first] += pi.second * coef;
}
}
return ret;
}
void solve(const string& s) {
vector<string> ret = split(s,'=');
vector<string> pre = split(ret[0],'+');
vector<string> suf = split(ret[1],'+');
map<string,int> pre_cnt = resolve(pre);
map<string,int> suf_cnt = resolve(suf);
bool r =cmp(pre_cnt, suf_cnt);
if (r) {
cout << "Y\n";
} else {
cout << "N\n";
}
}
int main() {
std::ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
solve(s);
}
}