标签:HDU sta ss top 4192 Guess pop int si
地址:http://acm.hdu.edu.cn/showproblem.php?pid=4192
思路:首先将中缀表达式转为后缀表达式,然后将数组全排列取计算每一个排列的后缀表达式的值即可
Code:
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
int n;
int d[55];
stack<string> sta;
string transform(string s){
string ss="",si;
int len=s.size();
while(!sta.empty()){
sta.pop();
}
for(int i=0;i<len;)
{
si=s[i++];
if(si.size()==1&&(si=="+"||si=="-"||si=="*"||si=="/"||si=="("||si==")")){
if(si==")"){
if(sta.top()!="("){
ss=ss+sta.top(); sta.pop();
}
sta.pop();
}else{
if((si=="+"||si=="-")&&!sta.empty()&&(sta.top()=="+"||sta.top()=="-")){
ss=ss+sta.top(); sta.pop();
}
sta.push(si);
}
}else{
ss=ss+si;
if(!sta.empty()&&(sta.top()=="*"||sta.top()=="/")){
ss=ss+sta.top(); sta.pop();
}
}
}
if(!sta.empty()){
ss=ss+sta.top(); sta.pop();
}
return ss;
}
int calculate(string s){
int t=0,a,b;
stack<int> stai;
for(int i=0;i<s.size();++i)
{
if(s[i]>='a'&&s[i]<='z'){
stai.push(d[t++]);
}else{
b=stai.top(); stai.pop();
a=stai.top(); stai.pop();
if(s[i]=='+') a+=b;
else if(s[i]=='-') a-=b;
else if(s[i]=='*') a*=b;
else a/=b;
stai.push(a);
}
}
return stai.top();
}
int main()
{
int ans;
string s,ss;
while(cin>>n&&n){
for(int i=0,x;i<n;++i)
{
cin>>x;
d[i]=x;
}
cin>>ans>>s;
ss=transform(s);
int m=1;
for(int i=1;i<=n;++i)
m*=i;
string res="NO";
while(m--){
if(calculate(ss)==ans){
res="YES"; break;
}
next_permutation(d,d+n);
}
cout<<res<<endl;
}
return 0;
}
标签:HDU,sta,ss,top,4192,Guess,pop,int,si 来源: https://blog.csdn.net/C_13579/article/details/111357212
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。