题解 | #24点运算#

24点运算

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

//
#include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;

int cal(int a,int b,char c)
{
    switch(c)
    {
        case '+':return a+b;
        case '-':return a-b;
        case '*':return a*b;
        case '/':return a/b;
    }
    return 0;
}

void func(vector<int> &vec)
{
    unordered_map<int,string> hash={
        {2,"2"},
        {3,"3"},
        {4,"4"},
        {5,"5"},
        {6,"6"},
        {7,"7"},
        {8,"8"},
        {9,"9"},
        {10,"10"},
        {11,"J"},
        {12,"Q"},
        {13,"K"},
        {1,"A"},
    };
    char op[4]={'+','-','*','/'};
    sort(vec.begin(),vec.end());
    do{
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<4;j++)
            {
                for(int k=0;k<4;k++)
                {
                    int first=cal(vec[0],vec[1],op[i]);
                    int second=cal(first,vec[2],op[j]);
                    if(cal(second,vec[3],op[k])==24)
                    {
                        cout<<hash[vec[0]]<<op[i]<<hash[vec[1]]<<op[j]<<hash[vec[2]]<<op[k]<<hash[vec[3]];
                        return;
                    }
                }
            }
        }
    }while(next_permutation(vec.begin(),vec.end()));
    cout<<"NONE"<<endl;
}

int main()
{
    unordered_map<char,int> hash={
        {'2',2},
        {'3',3},
        {'4',4},
        {'5',5},
        {'6',6},
        {'7',7},
        {'8',8},
        {'9',9},
        {'1',10},
        {'J',11},
        {'Q',12},
        {'K',13},
        {'A',1},
    };
    
    string str;
    while(getline(cin,str))
    {
        if(str.find("joker")!=-1 || str.find("JOKER")!=-1)
        {
            cout<<"ERROR"<<endl;
        }
        else
        {
            vector<int> vec;
            for(int i=0;i<str.size();i++)
            {
                if(str[i]!=' ')
                {
                    vec.push_back(hash[str[i]]);
                }
            }
            
            func(vec);
        }           
    }
        
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务