因为有些根本计算不出来。
比如:
1 4 5 6 6/(5/4-1)
1 5 5 5 5*(5-1/5)
2 4 10 10 10*(2+4/10)
3 3 8 8 8/(3-8/3)
考虑小数就可以了。注意浮点运算有时候不准,答案需要让它与24的差的绝对值小于一个很小的数,而不是等于0.
也就是对每一个数进行出来穷举出来
然后就有6种
+有一种 *有一种
-有两种 /有两种 (被减数和减数),(被除数和除数);
然后就是递归啦。。。
但是要把每种排列的方法穷举出来在进行递归。。。。。
(我懒想,直接用了4个循环)。
有一个小漏洞,就是1/3=0.3333333 所以最后答案有可能不是24 而是23.99999999所以在判断的时候判断是不是在+-0.0000001 之内!
我AC了后发现了个问题,就是数据里面没有10!
要是有10的话我的读入就有问题了。
程序如下,供大牛门鄙视:
program li;
var s:string;
a,b:array[1..10] of real;
i,j,k,t:longint;
procedure try(s:char;var a:real);
begin
case s of
'A': a:=1; 'J': a:=11; 'Q': a:=12; 'K': a:=13; end;
if a=0 then a:=ord(s)-48;
end;
procedure work(n:longint);
var temp:real;
begin
if n=1 then
if abs(a[1]-24)<0.0000001 then begin writeln('yes'); halt; end else exit;
if a[1]=0 then exit;
temp:=a[1];
a[1]:=a[n]+a[1]; work(n-1); a[1]:=temp;
a[1]:=a[1]-a[n]; work(n-1); a[1]:=temp;
a[1]:=a[n]-a[1]; work(n-1); a[1]:=temp;
a[1]:=a[1]*a[n]; work(n-1); a[1]:=temp;
if a[n]<>0 then begin
a[1]:=a[1] /a[n]; work(n-1); a[1]:=temp;
a[1]:=a[n] /a[1]; work(n-1); a[1]:=temp; end;
end;
begin
readln(s);
try(s[1],b[1]); try(s[3],b[2]); try(s[5],b[3]); try(s[7],b[4]);
for i:=1 to 4 do
for j:=1 to 4 do
if i<>j then
for k:=1 to 4 do
if (k<>i) and (k<>j) then
for t:=1 to 4 do
if (t<>i) and (t<>j) and (t<>k) then
begin a[1]:=b[i]; a[2]:=b[j]; a[3]:=b[k]; a[4]:=b[t]; work(4); end;
writeln('no');
end.
#include <cstdio>
#include <cstring>
typedef char String[20];
int a[4], b[4], path[4][2];
String ans[4], buf, Min = "zzzzz";
char op[4], Data[4];
void outit() {
int i;
for (i = 0; i < 4; i ++)
sprintf(ans[i], "%c", Data[i]);
for (i = 0; i < 3; i ++) {
sprintf(buf, "(%s%c%s)", ans[path[i][0]], op[i], ans[path[i][1]]);
strcpy(ans[path[i][0]], buf);
}
if (strcmp(Min, ans[path[2][0]]) > 0)
strcpy(Min, ans[path[2][0]]);
}
void dfs(int l) {
if (l == 3) {
int i;
for (i = 0; i < 4; i ++)
if (a[i] != 0) break;
if (i < 4 && a[i] == 24) outit();
return;
}
for (int i = 0; i < 4; i ++)
for (int j = 0; j < 4; j ++)
if (i != j && a[i] != 0 && a[j] != 0) {
int t1, t2;
t1 = a[i]; t2 = a[j];
a[i] = a[i] + a[j]; a[j] = 0;
path[l][0] = i; path[l][1] = j; op[l] = '+';
dfs(l + 1);
a[i] = t1; a[j] = t2;
t1 = a[i]; t2 = a[j];
a[i] = a[i] - a[j]; a[j] = 0;
path[l][0] = i; path[l][1] = j; op[l] = '-';
dfs(l + 1);
a[i] = t1; a[j] = t2;
t1 = a[i]; t2 = a[j];
a[i] = a[i] * a[j]; a[j] = 0;
path[l][0] = i; path[l][1] = j; op[l] = '*';
dfs(l + 1);
a[i] = t1; a[j] = t2;
if (a[i] % a[j] == 0) {
t1 = a[i]; t2 = a[j];
a[i] = a[i] / a[j]; a[j] = 0;
path[l][0] = i; path[l][1] = j; op[l] = '/';
dfs(l + 1);
a[i] = t1; a[j] = t2;
}
}
}
int main() {
char ch;
memset(path, -1, sizeof(path));
for (int i = 0; i < 4; i ++) {
scanf("%c ", &ch);
Data[i] = ch;
if (ch == 'A') a[i] = 1;
else if (ch == 'T') a[i] = 10;
else if (ch == 'J') a[i] = 11;
else if (ch == 'Q') a[i] = 12;
else if (ch == 'K') a[i] = 13;
else a[i] = ch - '0';
}
memcpy(b, a, sizeof(a));
dfs(0);
if (Min[0] == 'z'&&Min[0]=='z') printf("no\n");
else printf("yes\n");
return 0;
}