速算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 <cstdio>
#include <algorithm>
using namespace std;
const int INF=100000007;
int a[4];
char s[2];
//数字转换
int toNum(char s[]){
if(s[0]=='A'){
return 1;
}
else if(s[0]=='1' && s[1]=='0'){
return 10;
}
else if(s[0]=='J'){
return 11;
}
else if(s[0]=='Q'){
return 12;
}
else if(s[0]=='K'){
return 13;
}
else{
return s[0]-'1'+1;
}
}
//将数字全排列转化为运算符 注意除法的判断
int toOpe(int i,int m,int n){
if(i==0){
return m+n;
}
else if(i==1){
return m-n;
}
else if(i==2){
return m*n;
}
else if(i==3){
if(n==0 || m%n!=0){
return INF;
}
else{
return m/n;
}
}
}
bool calculate(int i,int j,int k){
//括号只有两种组合
//
int res1=toOpe(k,toOpe(j,toOpe(i,a[0],a[1]),a[2]),a[3]);
int res2=toOpe(k,toOpe(i,a[0],a[1]),toOpe(j,a[2],a[3]));
//这里要判断-24 否则会WA
if(res1==24 || res2==24 || res1==-24 || res2==-24){
return true;
}
else{
return false;
}
}
int main(void){
while(~scanf("%s",s)){
a[0]=toNum(s);
for(int i=1;i<=3;i++){
scanf("%s",s);
a[i]=toNum(s);
}
bool flag=false;
sort(a,a+4);
//排序
//for循环用来枚举运算符的组合
//next_permutation()用来枚举数字组合
//calculate函数用来计算两种括号组合
do{
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
for(int k=0;k<4;k++){
if(calculate(i,j,k)){
flag=true;
}
}
}
}
}while(next_permutation(a,a+4) && !flag);
if(flag){
printf("Yes\n");
}
else{
printf("No\n");
}
}
return 0;
}