24 point algorithm, the idea is the expression tree, 4 digits, 3 symbols can only build two kinds of trees, it is still difficult to go heavy, it is regrettable #include <stdio.h> int data[5];//stores the 4 digital int b[5];//storage Symbols I entered at the beginning
NT A[5];//a[1] is the first output of the number, and so on, so a[1~4] should correspond to the number of data[1~4] in the digital int sum;//statistics How many methods char ch[5]={'. ', ' + ', '-', ' * ', '/'};
int f (int c,int D,int k) {if (k==1) return c+d;
if (k==2) return c-d;
if (k==3) return c*d;
if (k==4) if ((d!=0) && (c%d==0)) return C/D; return-10000;//otherwise return a certain number that cannot be established} void Print1 () {if (b[1]>2) && (b[2]<3) printf ((%d%c%d), a
[1],ch[b[2]],a[2]);
else printf ("%d%c%d", a[1],ch[b[2]],a[2]);
printf ("%c", ch[b[1]);
if ((b[1]>2) && (b[3]<3)) printf ("(%d%c%d) =24\n", a[3],ch[b[3]],a[4]);
else printf ("%d%c%d=24\n", a[3],ch[b[3]],a[4]); void Print2 () {if ((b[2]<3) && (b[1]>2)) printf ("(%d%c%d%c%d)%c%d=24\n", a[1],ch[b[3]],a[2
],CH[B[2]],A[3],CH[B[1]],A[4]); ELSE if ((B[2]>2) && (b[3]<3)) printf ("(%d%c%d)%c%d%c%d=24\n", a[1],ch[b[3]],a[2],ch[b[2]],
A[3],CH[B[1]],A[4]);
else printf ("%d%c%d%c%d%c%d=24\n", a[1],ch[b[3]],a[2],ch[b[2]],a[3],ch[b[1]],a[4]);
} void Solve () {int i,j,k,p;
for (i=1;i<=4;i++) for (j=1;j<=4;j++) for (k=1;k<=4;k++) for (p=1;p<=4;p++) {if ((i+j+k+p==10) && (i*j*k*p==24))//If I,J,K,P is all aligned (within 1234, a+b+c+d=10 and a*b*c*d=24 have only one set of solutions, you can also directly Judge A[1]!=a
[2]!=a[3]!=a[4]) {a[1]=data[i];
A[2]=DATA[J];
A[3]=DATA[K];
A[4]=DATA[P];
if (f (f (a[1],a[2],b[2)), F (a[3],a[4],b[3]), b[1]) ==24)//For 4 numbers, 3 symbols have only two expression trees {sum++;
Print1 ();
} if (f (f (a[1],a[2],b[3), a[3],b[2]), a[4],b[1]) ==24) {sum++;
Print2 (); int main () {int i,j,k;
for (i=1;i<=4;i++) scanf ("%d", &data[i]);
sum=0;
for (i=1;i<=4;i++)//1 is addition, 2 is subtraction, 3 is multiplication, 4 is division for (j=1;j<=4;j++) for (k=1;k<=4;k++) {
B[1]=i;
B[2]=j;
B[3]=k;
Solve ();
} if (sum==0) printf ("No Solution ~~\n");
return 0;
}
Two expressions of the tree