题意:给出四张扑克牌 问能否算出24
思路:http://blog.csdn.net/xingyeyongheng/article/details/11137631
其实这题只有两种运算顺序
1([email protected])@[email protected]
2 ([email protected])@([email protected])
所以只需要把数字和运算符全排列遍历一边就可以判断出结果
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int num[5],ok; const int INF=100000; int change_num(char a) { if(a==‘A‘) return 1; else if(a==‘J‘) return 11; else if(a==‘Q‘) return 12; else if(a==‘K‘) return 13; if(a==‘1‘) return 10; else return a-‘0‘; } int fun2(int a,int op,int b) { if(op==0) { return a+b; } else if(op==1) { return a-b; } else if(op==2) { return a*b; } else if(op==3) { if(b==0||a%b!=0 )return INF; return a/b; } } void fun1(int i,int j,int k) { if(ok==1) return; int t1,t2,t3; t1=fun2(num[0],i,num[1]); if(t1!=INF) { t2=fun2(t1,j,num[2]); if(t2!=INF) { t3=fun2(t2,k,num[3]); if(t3==24||t3==-24) ok=1; } } if(ok==0) { t1=fun2(num[0],i,num[1]); t2=fun2(num[2],j,num[3]); if(t1!=INF&&t2!=INF) { t3=fun2(t1,k,t2); if(t3==24||t3==-24) ok=1; } } } int main() { int i,j,k; char temp[5]; while(scanf("%s",temp)!=EOF) { ok=0; num[0]=change_num(temp[0]); for(i=1;i<=3;i++) { scanf("%s",temp); num[i]=change_num(temp[0]); } sort(num,num+4); do { for(i=0;i<4;i++) { for(j=0;j<4;j++) { for(k=0;k<4;k++) { fun1(i,j,k); } } } if(ok==1) break; }while (next_permutation(num,num+4)); if(ok==1) printf("Yes\n"); else printf("No\n"); } return 0; }
时间: 2024-10-05 12:12:02