题解 | #24点运算#

24点运算

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

#include <bits/stdc++.h>
using namespace std;
map<char, int> mp;
int num[4];
char operation[4];
bool vis[4];
bool get(int a, int b, char& op1) {
    if (a + b == 24) { op1 = '+'; return true; }
    if (a - b == 24) { op1 = '-'; return true; }
    if (a * b == 24) { op1 = '*'; return true; }
    if (a / b == 24) { op1 = '/'; return true; }
    return false;
}

bool get(int a, int b, int c, char& op1, char& op2) {
    if (get(a + b, c, op2)) { op1 = '+'; return true; }
    if (get(a - b, c, op2)) { op1 = '-'; return true; }
    if (get(a * b, c, op2)) { op1 = '*'; return true; }
    if (get(a / b, c, op2)) { op1 = '/'; return true; }
    return false;
}

bool get(int a, int b, int c, int d, char& op1, char& op2, char& op3) {
    if (get(a + b, c, d, op2, op3)) { op1 = '+'; return true; }
    if (get(a - b, c, d, op2, op3)) { op1 = '-'; return true; }
    if (get(a * b, c, d, op2, op3)) { op1 = '*'; return true; }
    if (get(a / b, c, d, op2, op3)) { op1 = '/'; return true; }
    return false;
}

int main() {
    string s;
    mp['J'] = 11, mp['Q'] = 12, mp['K'] = 13, mp['A'] = 1;
    map<int, char> mp2;
    mp2[11] = 'J', mp2[12] = 'Q', mp2[13] = 'K', mp2[1] = 'A';
    while (getline(cin, s)) {
        if (s.find("joker") != string::npos || s.find("JOKER") != string::npos) {
            cout << "ERROR" << endl;
            continue;
        }
        stringstream ss(s);
        int cnt = 0;
        string tmp;
        while (getline(ss, tmp, ' ')) {
            if (!mp[tmp[0]])
                num[cnt++] = stoi(tmp);
            else
                num[cnt++] = mp[tmp[0]];
        }
        sort(num, num + 4);
        int flag = 0;
        char op[3];
        do {
            if(num[0]==11&&num[1]==13&&num[2]==1&&num[3]==6)
                int i=0;
            if (get(num[0], num[1], num[2], num[3], op[0], op[1], op[2])) {
                if (mp2[num[0]]) cout << mp2[num[0]];
                else cout<<num[0];
                for (int i = 1; i < 4; i++) {
                    cout << op[i - 1];
                    if (mp2[num[i]])
                        cout << mp2[num[i]];
                    else
                        cout << num[i];
                }
                cout << "\n";
                flag = 1;
                break;
            }
        } while (next_permutation(num, num + 4));
        if (!flag)
            cout << "NONE" << endl;
    }


}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务