湖南多校对抗赛(2015.05.03)Problem A: Twenty-four point
给四个数 问能不能算出24点。。。我的方法比较烂。。。920ms 差点TLE。应该有更好的方法。
#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; double a[5], ff[5], n; double rt[30][5], yy[5]; int sum; double get(double x, double y, int fu) { if (fu == 1) return x + y; if (fu == 2) return x - y; if (fu == 3) return x * y; if (fu == 4) return x / y; } void dfs(int tot) { int ii; if (tot == 4) { rt[sum][1] = yy[0]; rt[sum][2] = yy[1]; rt[sum][3] = yy[2]; rt[sum][4] = yy[3]; sum++; return; } for (ii = 0; ii < 4; ii++) { if (ff[ii] == 0) { ff[ii] = 1; yy[tot] = a[ii]; dfs(tot + 1); ff[ii] = 0; } } } int main() { while (~scanf("%lf%lf%lf%lf", &a[0], &a[1], &a[2], &a[3])) { memset(ff, 0, sizeof(ff)); sum = 1; dfs(0); int i, j, k, g; int ans = 0; double linshi1 = 0, linshi2 = 0, linshi3 = 0; double z, x, c, v; for (i = 1; i <= 24; i++) { for (g = 1; g <= 4; g++) { for (k = 1; k <= 4; k++) { for (j = 1; j <= 4; j++) { z = rt[i][1]; x = rt[i][2]; c = rt[i][3]; v = rt[i][4]; linshi1 = get(z, x, g); linshi2 = get(linshi1, c, k); linshi3 = get(linshi2, v, j); if (fabs(linshi3 - 24)<0.0000001){ ans = 1; break; } linshi1 = get(z, x, g); linshi2 = get(c, v, j); linshi3 = get(linshi1, linshi2, k); if (fabs(linshi3 - 24)<0.0000001){ ans = 1; break; } linshi1 = get(x, c, k); linshi2 = get(z, linshi1, g); linshi3 = get(linshi2, v, j); if (fabs(linshi3 - 24)<0.0000001){ ans = 1; break; } linshi1 = get(x, c, k); linshi2 = get(linshi1, v, j); linshi3 = get(z, linshi2, g); if (fabs(linshi3 - 24)<0.0000001){ ans = 1; break; } linshi1 = get(c, v, j); linshi2 = get(z, x, g); linshi3 = get(linshi1, linshi2, k); if (fabs(linshi3 - 24)<0.0000001){ ans = 1; break; } linshi1 = get(c, v, j); linshi2 = get(x, linshi1, k); linshi3 = get(z, linshi2, g); if (fabs(linshi3 - 24)<0.0000001){ ans = 1; break; } } if (ans) break; } if (ans) break; } if (ans) break; } if (ans == 1)printf("Yes\n"); else printf("No\n"); } return 0; }