题解 | #24点运算#

24点运算

http://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

暴力解决一切,既不优雅也不简洁

#include <algorithm>
#include <sstream>
#include <map>
#include <vector>

using namespace std;

bool judge(vector<int> &v,vector<string> &vchar,int result,int index){
    if(result==24&&index==4){
        return true;
    }
    int temp;
    if(index<4){
        bool cando = false;
        temp = result+v[index];
        vchar.push_back("+");
        cando = judge(v, vchar, temp, index+1);
        if(cando) return true;
        vchar.pop_back();//回溯
        temp = result-v[index];
        vchar.push_back("-");
        cando = judge(v, vchar, temp, index+1);
        if(cando) return true;
        vchar.pop_back();
        temp = result*v[index];
        vchar.push_back("*");
        cando = judge(v, vchar, temp, index+1);
        if(cando) return true;
        vchar.pop_back();
        temp = result/v[index];
        vchar.push_back("/");
        cando = judge(v, vchar, temp, index+1);
        if(cando) return true;
        vchar.pop_back();
    }
    return false;
}


int main() {
    string str;
    while(getline(cin,str)){
        istringstream ss;
        ss.str(str);
        map<string,int> m={
            {"2",2},
            {"3",3},
            {"4",4},
            {"5",5},
            {"6",6},
            {"7",7},
            {"8",8},
            {"9",9},
            {"10",10},
            {"J",11},
            {"Q",12},
            {"K",13},
            {"A",1},
        };
        vector<string> v;
        while(getline(ss,str,' ')){
            v.push_back(str);
        }
        string out;
        vector<int> vi;
        for(int i =0;i<4;i++){
            if(v[i]=="joker"||v[i]=="JOKER"){
                out = "ERROR";
                break;
            }
            vi.push_back(m[v[i]]);//保存int数值
        }
        if(out=="ERROR"){
            cout<<out<<endl;
            continue;//回到while
        }
        bool cando =false;
        sort(vi.begin(),vi.end());//准备做排列
        vector<string> vchar;//保存符号
        do{
            int result = vi[0];
            cando = judge(vi, vchar, result, 1);
            if(cando)break;
            vchar.clear();//这里cando是false,清空一下符号,准备下一次循环
        }while(next_permutation(vi.begin(),vi.end()));
        if(cando){
            vector<string> vtemp(4,"");
            for(int i = 0;i<4;i++){//找数字对应的符号
                if(m[v[i]]==vi[0])vtemp[0]=v[i];
                if(m[v[i]]==vi[1])vtemp[1]=v[i];
                if(m[v[i]]==vi[2])vtemp[2]=v[i];
                if(m[v[i]]==vi[3])vtemp[3]=v[i];
            }
            
        out+=vtemp[0];
        for(int i = 0;i<3;i++){
            out+=vchar[i]+vtemp[i+1];
        }
            cout<<out<<endl;
        }
        else{
            cout<<"NONE"<<endl;
        }
    }//while
}
全部评论

相关推荐

过往烟沉:我说什么来着,java就业面就是广!
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务