dfs:24点

博客探讨了如何使用深度优先搜索(DFS)策略解决数学游戏24点,介绍了相关题目和原创解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xxcc 题 目 传 送 门 x x c c


题目

传说,小圆搜题上有一个24点排位赛……


标程

#include <bits/stdc++.h>

const double EPS = 1e-6;

struct Ans{
    double x, y;
    int opt;
    double res;
} ans[3];

double a[4];

int sgn(double x) {
    if (x > EPS) return 1;
    if (x < -EPS) return -1;
    return 0;
}

char toChar(int opt) {
    return opt == 0 ? '+' : opt == 1 ? '-' : opt == 2 ? '*' : '/';
}

void print() {
    puts("-----------------------------------------");
    for (int i = 0; i < 3; i++) {
        printf("%.2lf %c %.2lf = %.2lf\n", ans[i].x, toChar(ans[i].opt), ans[i].y, ans[i].res);
    }
    puts("-----------------------------------------");
    puts("");
}

double calc(double x, double y, int opt) {
    switch (opt) {
        case 0: return x + y;
        case 1: return x - y;
        case 2: return x * y;
        case 3: return x / y;
    }
}

bool die;

void dfs(int dep) {
    if (die) return;
    if (dep == 1) {
        print();
        die = true;
        return;
    }
    double b[4];
    memcpy(b, a, sizeof(b));
    for (int i = 0; i < dep; i++) {
        for (int j = 0; j < dep; j++) {
            if (i == j) continue;
            for (int k = 0; k < 4; k++) {
                if (sgn(a[j]) == 0 && k == 3) continue;
                double res = calc(a[i], a[j], k);
                if (dep == 2 && sgn(res - 24)) continue;
                ans[4-dep] = (Ans){a[i], a[j], k, res};
                int ti = i, tj = j;
                if (ti > tj) std::swap(ti, tj);
                a[ti] = res;
                if (tj < dep) std::swap(a[tj], a[dep-1]);
                sort(a, a + dep - 1, std::greater<int>());
                dfs(dep-1);
                memcpy(a, b, sizeof(a));
            }
        }
    }
}

void solve() {
    sort(a, a + 4, std::greater<int>());
    die = false;
    dfs(4);
    if (!die) {
        puts("-----------------------------------------");
        puts("No solution.");
        puts("-----------------------------------------");
        puts("");
    }
}

int main() {
    while (std::cin >> a[0] >> a[1] >> a[2] >> a[3]) {
        solve();
    }
    return 0;
}

这是原创,不是转载……


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值