简介

使用回溯 + 暴力

code

#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
bool flag = false;
char v[4]={'+', '-', '*', '/'};
string mm[14] = {"0", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
int calc(char x, int a, int b){
    switch(x){
        case '+': return a+b;
        case '-': return a-b;
        case '*': return a*b;
        case '/': return b == 0 ? 1111111 : a/b;
    }
}
bool check(vector<int> &path){
    for(int j=0; j<4; j++){
        int ee = calc(v[j], path[0], path[1]);
        if(ee == 1111111) continue;
        for(int k=0; k<4; k++) {
            int ff = calc(v[k], ee, path[2]);
            if(ff == 1111111) continue;
            for(int l=0; l<4; l++){
                int gg = calc(v[l], ff, path[3]);
                if(gg == 1111111) continue;
                if(gg == 24) {
                    cout << mm[path[0]] << v[j] << mm[path[1]] << v[k] << mm[path[2]] << v[l] <<
                         mm[path[3]] << endl; 
                    return true;
                }
            }
        }
    }
    return false;
}
void dfs(vector<int> &v, map<int, bool> &vis, vector<int> &path){
    if(path.size() == v.size()) {
        flag = check(path);
        return;
    }
    for(int i=0; i<4; i++){
        if(flag) {
            return;
        }
        if(vis[i] == false) {
            vis[i] = true;
            path.push_back(v[i]);
            dfs(v, vis, path);
            if(flag) {
                return;
            }
            path.pop_back();
            vis[i] = false;
        }
    }
}
int main() {
    string a, b, c, d;
    map<string, int> m;
    m["2"] = 2;
    m["3"] = 3;
    m["4"] = 4;
    m["5"] = 5;
    m["6"] = 6;
    m["7"] = 7;
    m["8"] = 8;
    m["9"] = 9;
    m["10"] = 10;
    m["A"] = 1;
    m["J"] = 11;
    m["Q"] = 12;
    m["K"] = 13;

    int aa, bb, cc, dd;
    
    while(cin >> a >> b >> c >> d) {
        if(a == "joker" || b == "joker" || c == "joker" || d=="joker") {
            cout << "ERROR\n";
            continue;
        }
        vector<int> vv(4);
        vv[0] = m[a];
        vv[1] = m[b];
        vv[2] = m[c];
        vv[3] = m[d];
        map<int, bool> vis;
        vector<int> path;
        dfs(vv, vis, path);
        if(!flag) cout << "NONE\n";
    }
    
}
posted on 2021-06-27 15:12  HDU李少帅  阅读(41)  评论(0编辑  收藏  举报