我的做法是把中缀的表达式转换成后缀的便于计算
#include <iostream>
#include <cstdio>
#include <memory.h>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
using namespace std;
vector<char>opStak;
vector<string>ophStak;
queue<string>expQueue;
int opLev[128];
bool cnt1[128],cnt2[128];
void init(){
opStak.clear();
ophStak.clear();
while(expQueue.size())expQueue.pop();
opLev['+']=1,opLev['-']=1;
opLev['*']=2;opLev['(']=0;
}
void pre(string &s1,string &s2){
memset(cnt1,0,sizeof(cnt1));
memset(cnt2,0,sizeof(cnt2));
for (int i=0;i<s1.size();++i){
cnt1[s1[i]]=1;
}
for (int i=0;i<s2.size();++i){
cnt2[s2[i]]=1;
}
}
string uni(string & s1,string &s2){
pre(s1,s2);
string ans;
for (int i='A';i<='Z';++i){
if(cnt1[i]||cnt2[i]){
ans+=i;
}
}
return ans;
}
string intersec(string &s1,string &s2){
pre(s1,s2);
string ans;
for (int i='A';i<='Z';++i){
if(cnt1[i]&&cnt2[i]){
ans+=i;
}
}
return ans;
}
string diff(string & s1,string &s2){
pre(s1,s2);
string ans;
for (int i='A';i<='Z';++i){
if(cnt1[i]&&!cnt2[i]){
ans+=i;
}
}
return ans;
}
string calVal(){
while (expQueue.size()){
string exp=expQueue.front();
expQueue.pop();
if(exp.size()&&isupper(exp[0])||exp.size()==0){
ophStak.push_back(exp);
}else{
string s2=ophStak.back();
ophStak.pop_back();
string s1=ophStak.back();
ophStak.pop_back();
string ans;
if(exp[0]=='+'){
ans=uni(s1,s2);
}else if(exp[0]=='-'){
ans=diff(s1,s2);
}else{
ans=intersec(s1,s2);
}
ophStak.push_back(ans);
}
}
return ophStak.back();
}
void readExpression(){
char ch;
while (ch=getchar(),ch!='\n'){
if(ch=='{'){
string oph;
while(ch=getchar(),ch!='}'){
oph+=ch;
}
expQueue.push(oph);
}else if(ch==')'){
while (opStak.size()&&opStak.back()!='('){
string opt;
opt+=opStak.back();
expQueue.push(opt);
opStak.pop_back();
}
opStak.pop_back();
}else{
if(ch=='('){
opStak.push_back(ch);
continue;
}
while(opStak.size()&&opLev[opStak.back()]>=opLev[ch]){
string opt;
opt+=opStak.back();
expQueue.push(opt);
opStak.pop_back();
}
opStak.push_back(ch);
}
}
while (opStak.size()){
string opt;
opt+=opStak.back();
expQueue.push(opt);
opStak.pop_back();
}
}
int main(){
char ch;
while (cin>>ch){
cin.putback(ch);
init();
readExpression();
printf("{%s}\n",calVal().c_str());
}
return 0;
}