C简单的24点
输入为4个数字,a,b,c,d。若abcd=24,则称该数组满足24点,其中可以为+、-、*、/任一个,若不能得到结果24,则称该数组不满足24点。(计算为实型)
输入:
第一行为测试组数t
接下来t行,每一行为四个整数a,b,c,d,测试是否满足24点
1<=a,b,c,d<10000(右区间忘了,反正四个数不为0)
输出
在每一行
若满足,输出YES
不满足 则输出NO
#include
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<memory.h>
#include<string.h>
#include
#include
bool BFS(int a,int b,int c,int d) { // priority
for(int i=0; i<2; i++) { //a b 进行乘除,优先级必然更高,优先计算 、/ +、-、、/、 +、-、、/
double tmp=0;
if(i==0) tmp=ab;
if(i1) tmp=(double)a/(double)b;
double cnt=tmp;
for(int j=0; j<4; j++) {
tmp=cnt;
if(j0) tmp=tmp+c; //*** error:这是一个循环的,所以每次循环都要重新对tmp赋值
if(j1) tmp-=c;
if(j2) tmp*=c;
if(j3) tmp/=(double)c;
cnt=tmp;
// printf("%d\n",tmp);
for(int k=0; k<4; k++) { // for(int k=0; j<4; j++) 小心这样的错误
tmp=cnt;
if(k0) tmp=tmp+d;
if(k1) tmp-=d;
if(k2) tmp*=d;
if(k3) tmp/=(double)d;
if(tmp24) {
// printf("%d %d %d\n",i,j,k);
return true;
}
}
}
}
for(int i=0; i<2; i++) { /// +/- +/- +/- 优先级都是+- 从左至右一次进行
double tmp=0;
if(i==0) tmp=a+b;
if(i==1) tmp=a-b;
double cnt=tmp;
for(int j=0; j<2; j++) {
tmp=cnt;
if(j==0) tmp=tmp+c; //error:
if(j==1) tmp=tmp-c;
cnt=tmp;
// printf("%d\n",tmp);
for(int k=0; k<2; k++) {
tmp=cnt;
if(k==0) tmp=tmp+d;
if(k==1) tmp-=d;
if(tmp==24) {
// printf("+-+-%d %d %d\n",i,j,k);
return true;
}
}
}
}
for(int i=0; i<2; i++) { // +/- *、/ +/- 中间的优先级更高
double tmp=0;
if(i==0) tmp=b*c;
if(i==1) tmp=(double)b/(double)c;
double cnt=tmp;
for(int j=0; j<2; j++) {
tmp=cnt;
if(j==0) tmp=a+tmp; //error:
if(j==1) tmp=a-tmp;
cnt=tmp;
// printf("%d\n",tmp);
for(int k=0; j<2; j++) {
tmp=cnt;
if(k==0) tmp=tmp+d;
if(k==1) tmp-=d;
if(tmp==24) {
// printf("%+-*/d %d %d\n",i,j,k);
return true;
}
}
}
}
if(a+b*c*d==24) return true; //+ * *
if(a+(double)b/(double)c/(double)d==24) return true;
if(a+(double)b/(double)c*d==24) return true;
if(a+(double)b*(double)c/(double)d==24) return true;
if(a-b*c*d==24) return true; //- * *
if(a-(double)b/(double)c/(double)d==24) return true;
if(a-(double)b/(double)c*d==24) return true;
if(a-(double)b*(double)c/(double)d==24) return true;
if(a+b+c*d==24) return true; //+ + *
if(a+b+(double)c/(double)d==24) return true;
if(a+b-(double)c*(double)d==24) return true;
if(a+b-(double)c/(double)d==24) return true;
if(a-b+c*d==24) return true; //- + *
if(a-b+(double)c/(double)d==24) return true;
if(a-b-(double)c*(double)d==24) return true;
if(a-b-(double)c/(double)d==24) return true;
return false;
}
int main() {
#ifdef ONLINE_JUDGE
#else
freopen(“18PC 24点.txt”, “r”, stdin);
#endif
/* your code */
int t;
while(scanf("%d",&t)!=EOF) {
while(t–) {
int a,b,c,d;
scanf("%d %d %d %d",&a,&b,&c,&d);
bool flag=BFS(a,b,c,d);
if(flag==true) printf(“YES\n”);
else printf(“NO\n”);
}
}
return 0;
}