题目大意
给你四个数字,问你能否经过加减乘除使其结果为24
解题思路
先暴力枚举四个数字的全排列,然后枚举运算符和括号
代码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
int t, ans, p[10], ss[10], s[10], v[10];
void dfs2(int x)
{if (!x){if (s[1] == 24) ans = 1;return;}int g[10], gg[10];for (int i = 1; i <= x; ++i)g[i] = s[i], gg[i] = v[i];for (int i = 1; i <= x; ++i)//枚举括号,就是枚举先算哪个运算符{if (v[i] == 1) s[i] += s[i + 1];else if (v[i] == 2) s[i] -= s[i + 1];else if (v[i] == 3) s[i] *= s[i + 1];else if (!s[i + 1]) continue;//除数不为0else if (s[i] % s[i + 1]) continue;//只能整除else s[i] /= s[i + 1];for (int j = i + 1; j <= x; ++j)s[j] = s[j + 1], v[j - 1] = v[j];//把后面的往前移dfs2(x - 1);if (ans) return;for (int j = 1; j <= x; ++j)//回溯s[j] = g[j], v[j] = gg[j];}
}
void dfs1(int x)
{if (x == 4){dfs2(3);return;}for (int i = 1; i <= 4; ++i)//枚举符号{v[x] = i;dfs1(x + 1);if (ans) return;}
}
void dfs3(int x)
{if (x > 4){dfs1(1);return;}for (int i = 1; i <= 4; ++i)//枚举全排列if (!p[i]){s[x] = ss[i];p[i] = 1;dfs3(x + 1);p[i] = 0;}
}
int main()
{scanf("%d", &t);while(t--){scanf("%d%d%d%d", &ss[1], &ss[2], &ss[3], &ss[4]);ans = 0;dfs3(1);printf("%d\n", ans);}return 0;
}