P1008 [NOIP 1998 普及组] 三连击题解

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 定义一个结构体来存储满足条件的三个三位数
struct Triple {
    int num1, num2, num3;
};

// 深度优先搜索函数
// step表示当前处理的数字位置
// a数组用于存储数字排列
// book数组用于标记数字是否已使用
// result用于存储满足条件的组合
void dfs(int step, int a[], bool book[], vector<Triple>& result) {
    // 当确定了9个数字的排列时,检查是否满足条件
    if (step == 10) {
        // 计算三个三位数
        int num1 = a[1] * 100 + a[2] * 10 + a[3];
        int num2 = a[4] * 100 + a[5] * 10 + a[6];
        int num3 = a[7] * 100 + a[8] * 10 + a[9];
        // 检查是否满足1:2:3的比例关系
        if (num2 == num1 * 2 && num3 == num1 * 3) {
            // 如果满足,将组合存入结果中
            result.push_back({num1, num2, num3});
        }
        return;
    }

    // 遍历1到9的数字
    for (int i = 1; i <= 9; ++i) {
        // 如果数字i未被使用
        if (!book[i]) {
            // 将数字i放入当前位置
            a[step] = i;
            // 标记数字i已使用
            book[i] = true;
            // 继续下一个位置的搜索
            dfs(step + 1, a, book, result);
            // 回溯,将数字i标记为未使用,以便进行其他尝试
            book[i] = false;
        }
    }
}

int main() {
    int a[10];
    bool book[10] = {false};
    vector<Triple> result;
    // 开始深度优先搜索
    dfs(1, a, book, result);

    // 按照第一个数字升序排序
    sort(result.begin(), result.end(), [](const Triple& t1, const Triple& t2) {
        return t1.num1 < t2.num1;
    });

    // 输出满足条件的组合
    for (const auto& triple : result) {
        cout << triple.num1 << " " << triple.num2 << " " << triple.num3 << endl;
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值