最近写题都是呕心沥血的状态。。。。。。。。╮(╯▽╰)╭
给出n个数据,和m,再给出一个含有n个变量的表达式,问是否存在一种排列方式将数据代入变量,使得表达式的结果等于m。
需要考虑的是运算符号和括号的优先级。这里我存的是优先级1最大。有一些小注意点。
http://www.lxway.com/648466146.htm
http://acm.hdu.edu.cn/showproblem.php?pid=4192
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<map>
#include<cmath>
#include<stack>
#include<stdlib.h>
#include<cstdio>
#define ll long long
using namespace std;
int n,m;
map<char,int> r;
int y[50];
int main(){
r[')']=4; //优先级最小,压在栈的最下面
r['(']=3;
r['+']=2;
r['-']=2;
r['*']=1;
while(cin>>n&&n!=0){
int u=0;
for(int i=0;i<n;++i)
cin>>y[i];
sort(y,y+n);
cin>>m;
string x;
cin>>x;
x='('+x;
x+=')';
do{
int c=-1;
stack<char> st;
stack<int> stk;
for(int i=0;i<x.length();++i){
if(x[i]>='a'&&x[i]<='z')
stk.push(y[++c]);
else if(x[i]=='(')
st.push(x[i]);
else{
while(!st.empty()&&r[x[i]]>=r[st.top()]){
int g;
if(st.top()=='*'){
g=stk.top();
stk.pop();
g*=stk.top();
stk.pop();
stk.push(g);
}
else if(st.top()=='-'){
g=stk.top();
stk.pop();
g=stk.top()-g; //这里稍微注意一下
stk.pop();
stk.push(g);
}
else if(st.top()=='+'){
g=stk.top();
stk.pop();
g+=stk.top();
stk.pop();
stk.push(g);
}
else if(st.top()=='('){
st.pop();
break;
}
st.pop();
}
if(x[i]!=')')
st.push(x[i]);
}
}
if(stk.top()==m){
u=1;
break;
}
}while(next_permutation(y,y+n));
if(u==1)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
cin>>m;
return 0;
}