题解 | #24点运算#

24点运算

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

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

//card to num
map<string, int> c2n = {
	{"3", 3},
	{"4", 4},
	{"5", 5},
	{"6", 6},
	{"7", 7},
	{"8", 8},
	{"9", 9},
	{"10", 10},
	{"J", 11},
	{"Q", 12},
	{"K", 13},
	{"A", 1},
	{"2", 2},
	{"joker", 16},
	{"JOKER", 17}
};

//number to card
map<int, string> n2c = {
	{3, "3"},
	{4, "4"},
	{5, "5"},
	{6, "6"},
	{7, "7"},
	{8, "8"},
	{9, "9"},
	{10, "10"},
	{11, "J"},
	{12, "Q"},
	{13, "K"},
	{1, "A"},
	{2, "2"},
	{16, "joker"},
	{17, "JOKER"}
};

int calc2(int a, int b, char op)
{
	switch (op)
	{
	case '+':
		return a + b;
	case '-':
		return a - b;
	case '*':
		return a * b;
	case '/':
		return a / b;
	default:
		break;
	}

	return -9999;
}

void calc24(vector<int> vcard)
{
	char op[4] = { '+', '-', '*', '/' };
	int sum1, sum2, sum3;

	do
	{
		for (int i = 0; i < 4; i++)
		{
			sum1 = calc2(vcard[0], vcard[1], op[i]);
			for (int j = 0; j < 4; j++)
			{
				sum2 = calc2(sum1, vcard[2], op[j]);
				for (int k = 0; k < 4; k++)
				{
					sum3 = calc2(sum2, vcard[3], op[k]);
					if (sum3 == 24)
					{
						cout << n2c[vcard[0]] << op[i] << n2c[vcard[1]] << op[j]
							<< n2c[vcard[2]] << op[k] << n2c[vcard[3]] << endl;
						return;
					}
				}
			}
		}
	} while (next_permutation(vcard.begin(), vcard.end()));

	cout << "NONE" << endl;
}

int main()
{
	vector<int> vcard;
	int flag = 0;

    for (int i = 0; i < 4; i++)
    {
        string tmp;
        cin >> tmp;
        if (tmp == "joker" || tmp == "JOKER")
        {
            flag = 1;
        }
        vcard.push_back(c2n[tmp]);
    }

    if (flag == 1)
    {
        cout << "ERROR" << endl;
    }

    calc24(vcard);
	
	return 0;
}

全部评论

相关推荐

某物流公司 软件开发岗 总包26-30
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务