hdu4192

12 篇文章 0 订阅

最近写题都是呕心沥血的状态。。。。。。。。╮(╯▽╰)╭

给出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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值