思路是先建立后缀表达式,然后扫一遍,如果出现0&或者1|就ans++;
#include <iostream>
#include <string>
#include <stack>
#include <vector>
using namespace std;
int n, ans1, ans2;
char res;
string s;
stack<char> op, num;
vector<char> v;
void build(){
for(int i=0; i<=n; i++){
if(s[i]=='0'||s[i]=='1'){
v.push_back(s[i]);
}
else if(s[i]=='('){
op.push(s[i]);
}
else if(s[i]==')'){
while(!op.empty() && op.top()!='('){
v.push_back(op.top());
op.pop();
}
op.pop();
}
else if(s[i]=='&'){
while(!op.empty() && op.top()=='&'){
v.push_back(op.top());
op.pop();
}
op.push(s[i]);
}
else if(s[i]=='|'){
while(!op.empty() && op.top()!='('){
v.push_back(op.top());
op.pop();
}
op.push(s[i]);
}
}
while(!op.empty()){
v.push_back(op.top());
op.pop();
}
}
void solve(){
for(int i=0; i<v.size(); i++){
if(v[i]=='0'||v[i]=='1'){
num.push(v[i]);
}
else if(v[i]=='&'){
char a=num.top();num.pop();
char b=num.top();num.pop();
char x='0';
if(a=='0')ans1++;
if(a=='1' && b=='1') x='1';
num.push(x);
}
else if(v[i]=='|'){
char a=num.top();num.pop();
char b=num.top();num.pop();
char x;
if(a=='1')ans2++;
if(a=='1' || b=='1') x='1';
num.push(x);
}
}
res=num.top();
}
int main()
{
cin>>s;
n=s.size()-1;
build();
solve();
cout<<res<<endl;
cout<<ans1<<" "<<ans2;
return 0;
}
p.s. 样例2过不了
%%%