题解 | #24点游戏算法#
24点游戏算法
http://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
#include<stdio.h> int visit[4] = {0,0,0,0}; int dfs(double arr[],double res_cur){ double r = res_cur-24; int sum = visit[0]+visit[1]+visit[2]+visit[3]; r = r<0?-r:r; if(r<=1e-6&&sum==4){ return 1; } for(int i=0;i<4;i++){ if(visit[i]==0){ visit[i] = 1; int r1 = dfs(arr,res_cur+arr[i]); int r2 = dfs(arr,res_cur-arr[i]); int r3 = dfs(arr,res_cur*arr[i]); int r4 = dfs(arr,res_cur/arr[i]); if(r1+r2+r3+r4){ return 1; } else visit[i] = 0; } } return 0; } int main(){ double arr[4]; while(scanf("%lf %lf %lf %lf",&arr[0],&arr[1],&arr[2],&arr[3])!=EOF){ memset(visit,0,sizeof(visit)); for(int i=0;i<4;i++){ scanf("%lf",&arr[i]); } double res_cur = 0; if(dfs(arr,res_cur)==1) printf("true"); else printf("false"); } }