Skip to content

Commit 8464c7c

Browse files
committed
Added C++ solution for 0770.Basic Calculator IV
1 parent b124017 commit 8464c7c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
struct Poly{
4+
map<vector<string>, long> d;
5+
Poly(long v=0){ if(v) d[{}]=v; }
6+
Poly(const string &s){ d[{s}]=1; }
7+
};
8+
Poly add(const Poly &a,const Poly &b){ Poly r=a; for(auto &p:b.d) r.d[p.first]+=p.second; for(auto it=r.d.begin();it!=r.d.end();){ if(it->second==0) r.d.erase(it++); else ++it;} return r; }
9+
Poly sub(const Poly &a,const Poly &b){ Poly r=a; for(auto &p:b.d) r.d[p.first]-=p.second; for(auto it=r.d.begin();it!=r.d.end();){ if(it->second==0) r.d.erase(it++); else ++it;} return r; }
10+
Poly mul(const Poly &a,const Poly &b){ Poly r; for(auto &p:a.d) for(auto &q:b.d){ auto v=p.first; v.insert(v.end(),q.first.begin(),q.first.end()); sort(v.begin(),v.end()); r.d[v]+=p.second*q.second; } for(auto it=r.d.begin();it!=r.d.end();){ if(it->second==0) r.d.erase(it++); else ++it;} return r; }
11+
class Solution {
12+
public:
13+
vector<string> basicCalculatorIV(string expr, vector<string>& evv, vector<int>& evi){
14+
unordered_map<string,long> mp;
15+
for(int i=0;i<evv.size();i++) mp[evv[i]] = evi[i];
16+
vector<string> toks;
17+
string t;
18+
for(char c:expr){
19+
if(c==' '){ if(!t.empty()){ toks.push_back(t); t.clear(); }}
20+
else if(strchr("()+-*",c)){
21+
if(!t.empty()){ toks.push_back(t); t.clear(); }
22+
toks.push_back(string(1,c));
23+
} else t.push_back(c);
24+
}
25+
if(!t.empty()) toks.push_back(t);
26+
int i=0;
27+
function<Poly()> parseE, parseT, parseP;
28+
parseP = [&]{ string s=toks[i++]; if(s=="("){ Poly r = parseE(); i++; return r;} if(isdigit(s[0])) return Poly(stol(s)); return mp.count(s)? Poly(mp[s]) : Poly(s); };
29+
parseT = [&]{ Poly r=parseP(); while(i<toks.size() && toks[i]=="*"){ i++; r = mul(r, parseP()); } return r; };
30+
parseE = [&]{ Poly r=parseT(); while(i<toks.size()&&(toks[i]=="+"||toks[i]=="-")){ string op=toks[i++]; Poly p=parseT(); r = (op=="+"? add(r,p) : sub(r,p)); } return r; };
31+
Poly res = parseE();
32+
vector<pair<vector<string>,long>> v(res.d.begin(), res.d.end());
33+
sort(v.begin(), v.end(), [](auto &a, auto &b){ if(a.first.size()!=b.first.size()) return a.first.size()>b.first.size(); return a.first<b.first; });
34+
vector<string> ans;
35+
for(auto &p:v) if(p.second){
36+
string s = to_string(p.second);
37+
for(auto &var:p.first) s += "*" + var;
38+
ans.push_back(s);
39+
}
40+
return ans;
41+
}
42+
};

0 commit comments

Comments
 (0)