24点(递归)

24点(递归)

#include <stdio.h>
#include <math.h>
void fuhao(int temp[], char ch[], int pos,int num[]);
int cal(int temp[], char ch[], int num[]);

char a[4] = {'+', '-', '*', '/'};
int flag = 0;//判断是否已有满足24点的情况

//对4个数的位置进行排序,共有24种情况
void sort(int num[], int temp[], int pos)
{
    if (pos == 4) {
        char ch[3];
        //4个数排序好后,开始选择运算符
        fuhao(temp, ch, 0, num);
        return;
    }
    for (int i = 0; i < 4; i++) {
        int j;
        for (j = 0; j < pos; j++) if (i == temp[j]) break;
        if(j == pos) {
            temp[pos] = i;
            sort(num, temp, pos + 1);
            if (flag == 1) return;
        }
    }
}

//选择3个符号插入4个数之间
void fuhao(int temp[], char ch[], int pos, int num[])
{
    if (pos == 3) {
        //选择好后,计算该表达式是否满足24点
        //满足则返回1,不满足则返回0
        //返回为1时,flag=1,表示已找到满足24的情况
        if (cal(temp, ch, num)) flag = 1;
        return;
    }
    for (int i = 0; i < 4; i++) {
        ch[pos] = a[i];
        fuhao(temp, ch, pos + 1,num);
        if (flag == 1) return;
    }
}

double suan(double a, double b, char hao)
{
    switch (hao)
    {
    case '+': return a + b;
    case '-': return a - b;
    case '*': return a * b;
    case '/': return a * 1.0 / b;
    }
}

//对该表达式的所有可能运算顺序进行计算,共有5种情况
int cal(int temp[], char ch[],int num[])
{
    double res;
    //(((①②) ③) ④)
    res = suan(num[temp[0]], num[temp[1]], ch[0]);
    res = suan(res, num[temp[2]], ch[1]);
    res = suan(res, num[temp[3]], ch[2]);
    if (fabs(res - 24) < 1e-12) return 1;
    //((① (②③)) ④)
    res = suan(num[temp[1]], num[temp[2]], ch[1]);
    res = suan(num[temp[0]], res, ch[0]);
    res = suan(res, num[temp[3]], ch[2]);
    if (fabs(res - 24) < 1e-12) return 1;
    //((① ((②③) ④)
    res = suan(num[temp[1]], num[temp[2]], ch[1]);
    res = suan(res, num[temp[3]], ch[2]);
    res = suan(num[temp[0]], res, ch[0]);
    if (fabs(res - 24) < 1e-12) return 1;
    //(① (② (③④)))
    res = suan(num[temp[2]], num[temp[3]], ch[2]);
    res = suan(num[temp[1]], res, ch[1]);
    res = suan(num[temp[0]], res, ch[0]);
    if (fabs(res - 24) < 1e-12) return 1;
    //((①②) (③④))
    res = suan(num[temp[0]], num[temp[1]], ch[0]);
    res = suan(res, suan(num[temp[2]], num[temp[3]], ch[2]), ch[1]);
    if (fabs(res - 24) < 1e-12) return 1;
    return 0;
}

int main()
{
    int n;
    scanf("%d", &n);
    while (n--) {
        int num[4], temp[4];
        for (int i = 0; i < 4; i++) scanf("%d", &num[i]);
        sort(num, temp, 0);
        if (flag == 1) {
            printf("True");
            flag = 0;
        }
        else printf("False");
        if (n != 0) printf(" ");
    }
	return 0;
}

 

上一篇:微信小程序的分包:


下一篇:Idea自动生成get()和set()方法的快捷操作