HDU - 1427 速算24点 (dfs,暴力)
速算24点
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7037 Accepted Submission(s): 1857
Problem Description
速算24点相信绝大多数人都玩过。就是随机给你四张牌,包括A(1),2,3,4,5,6,7,8,9,10,J(11),Q(12),K(13)。要求只用'+','-','*','/'运算符以及括号改变运算顺序,使得最终运算结果为24(每个数必须且仅能用一次)。游戏很简单,但遇到无解的情况往往让人很郁闷。你的任务就是针对每一组随机产生的四张牌,判断是否有解。我们另外规定,整个计算过程中都不能出现小数。
Input
每组输入数据占一行,给定四张牌。
Output
每一组输入数据对应一行输出。如果有解则输出"Yes",无解则输出"No"。
Sample Input
A 2 3 6
3 3 8 8
Sample Output
Yes
No
思路
由于没有运算顺序, 我们可以选择任意两个数进行加减乘除操作.
#include <bits/stdc++.h> using namespace std; int a[4]; bool vis[4], OK, flag; void dfs(int cur) { /* cout<<cur<<'\n'; for(int i=0;i<4;++i) { cout<<a[i]<<' '; } cout<<'\n';*/ if (OK) return; if (cur == 3) { for (int i = 0; i < 4; i++) if (vis[i] && a[i] == 24) OK = true; return; } for (int i = 0; i < 4; i++) if (vis[i]) for (int j = i + 1; j < 4; j++) if (vis[j]) { vis[j] = false; int x = a[i], y = a[j]; if (y != 0 && x % y == 0) a[i] = x / y, dfs(cur + 1); if (x != 0 && y % x == 0) a[i] = y / x, dfs(cur + 1); a[i] = x - y, dfs(cur + 1); a[i] = y - x, dfs(cur + 1); a[i] = x + y, dfs(cur + 1); a[i] = x * y, dfs(cur + 1); a[i] = x; vis[j] = true; } } int READ() { char c[4][4]; int res = scanf("%s%s%s%s", c[0], c[1], c[2], c[3]); for (int i = 0; i < 4; i++) { if (c[i][0] == 'A') a[i] = 1; else if (c[i][0] == 'J') a[i] = 11; else if (c[i][0] == 'Q') a[i] = 12; else if (c[i][0] == 'K') a[i] = 13; else if (c[i][0] == '1') a[i] = 10; else a[i] = c[i][0] - '0'; } memset(vis, true, sizeof(vis)); OK = false; return ~res; } int main() { #ifndef ONLINE_JUDGE // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); #endif while (READ()) { /* for(int i = 0; i < 4; i++) cout << a[i] << " "; cout << endl;*/ dfs(0); puts(OK ? "Yes" : "No"); } }