/*
以下代码仅给出
24点游戏一个解
或者判定其无解
*/
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define EPS 1e-8
#define DIN double /*或int*/
#define MAX 10 /* 或13 */
char strs[12],operator[]="+-*/",opch[][3]={"+","-","×","÷"};
DIN ans(int ith,DIN x,DIN y)
{ switch(operator[ith-1])
{ case '+': return x+y;
case '-': return x-y;
case '*': return x*y;
case '/': if(y)if(sizeof(DIN)==sizeof(int)&&(int)x%(int)y==0
||sizeof(DIN)==sizeof(double))return x/y;
default : return -1; }
}
int ok2(DIN x,DIN y)
{ int ix; for(ix=1; ix<=4; ix++)
if(fabs(ans(ix,x,y)-24)<EPS)return(ix);
return(0);
}
int ok3(DIN a,DIN b,DIN c)
{ int i,j,k; DIN x[3];
x[0]=a; x[1]=b; x[2]=c;
for(i=0; i<3; i++)
for(j=0; j<3; j++)if(j!=i)
for(k=0; k<3; k++)if(k!=i && k!=j)
{ int ix,imid; DIN y;
for(ix=1; ix<=4; ix++)
{ y=ans(ix,x[i],x[j]); if(y<=0)continue;
if((imid=ok2(y,x[k]))!=0)
{ if(i==0)printf("(%s%s%d)%s%d\n",strs,opch[ix-1],
(int)x[j],opch[imid-1],(int)x[k]);
else if(j==0)printf("(%d%s%s)%s%d\n",(int)x[i],opch[ix-1],
strs,opch[imid-1],(int)x[k]);
else if(k==0)printf("(%d%s%d)%s%s\n",(int)x[i],opch[ix-1],
(int)x[j],opch[imid-1],strs);
return(1);
}
}
} return(0);
}
int point24(int p[4])
{ int a,b,c,d,i,ix; DIN y;
for(a=0; a<4; a++)
for(b=0; b<4; b++)if(b!=a)
for(c=0; c<4; c++)if(c!=a && c!=b)
for(d=0; d<4; d++)if(d!=a && d!=b && d!=c)
for(ix=1; ix<=4; ix++)
{ y=ans(ix,p[a],p[b]); if(y<=0)continue;
strs[0]='('; itoa(p[a],&strs[1],10);
strcat(strs,opch[ix-1]); i=strlen(strs);
itoa(p[b], &strs[i],10); i=strlen(strs);
strs[i]=')'; strs[i+1]='\0';
if(ok3(y,p[c],p[d]))return(1);
} return(0);
}
main( )
{ int p[4],total,cannot; printf("4 cards: ");
scanf("%d%*c%d%*c%d%*c%d",p,p+1,p+2,p+3);
point24(p);
}