算24

xiaoxiao2021-02-28  59

输入:

输入数据多行,每行给出一组测试数据,包括4个小于10的正整数,最后一句测试数据中包括4个0,表示输入的结束,这组数据不做处理。

输出:

对于每一组测试数据,输出一行,如果可以得到24,输出“YES”,否则,输出 “NO”。

样例输入

5 5 5 1

1 1 4 2

0 0 0 0

样例输出

YES

NO

解析思路:

n个数算24,必有两个数要先算。这两个数算的结果和余下的n-2个数,就构成n-1个数求24的问题。

枚举先算的两个数,以及它们的运算方式

注意:可能有浮点数,精度不同,不可直接用==

#include<iostream> #include<cmath> using namespace std; double a[5]; #define EPS 1e-6 bool isZero(double x) { return fabs(x)<=EPS; } bool count24(double a[],int n) { //用数组a里的n个数,计算24 if(n==1)//最后一个数算24 { if(isZero(a[0]-24)) return true; else return false; } double b[5]; for(int i=0;i<n-1;i++) for(int j=i+1;j<n;j++)//枚举任意两个数 { int m=0; for(int k=0;k<n;k++) if(k!=i&&k!=j)//把余下的n-2个数放在数组b中 b[m++]=a[k]; b[m]=a[i]+a[j]; if(count24(b,m+1)) return true; b[m]=a[i]-a[j]; if(count24(b,m+1)) return true; b[m]=a[j]-a[i]; if(count24(b,m+1)) return true; b[m]=a[i]*a[j]; if(count24(b,m+1)) return true; if(!isZero(a[j])) { b[m]=a[i]/a[j]; if(count24(b,m+1)) return true; } if(!isZero(a[i])) { b[m]=a[j]/a[i]; if(count24(b,m+1)) return true; } } return false; } int main() { int n=0; while(1) { for(int i=0;i<4;i++) { scanf("%lf",&a[i]); if(a[i]==0)n++; } if(n==4) return 0; if(count24(a,4)) printf("YES"); else printf("NO"); } }

转载请注明原文地址: https://www.6miu.com/read-73706.html

最新回复(0)