题解:P15435 [蓝桥杯 2025 国 Python B] 免费披萨

· · 题解

明显,拿到题目就能看出来这是一道暴力题,题目的第一个规则可以直接转化为生成一个满足同时包含1~8的数

这一点我们可以直接使用C++的全排列函数next_permutation来解这一道题

主体思路是通过一个数组来枚举12345678的全排列,通过枚举x(任意一个1~8的数)的出现位置来实现

复杂度大致为

1-8 的全排列数:8!=40320 次

每个排列的操作:9 个插入位置 \times\space 8 个插入数字 = 72 次

总循环次数:40320×72=2903040 次(约 3\times 10^6 次)。

当然,真正的代码复杂度远比这样高,我的没经过优化的代码甚至达到了700ms,通过预处理和STL优化,可以压到300~500ms

废话不多说,直接上代码awa

#include<bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    int num[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // 1~8全排列
    int mx_gcd = INT_MIN, res = INT_MIN;
    do {
        int n8 = 0; // 全排列转换成8位数字
        for(int i = 0; i < 8; i++) {
            n8 = n8 * 10 + num[i];
        }
        string s = to_string(n8);
        for(int id = 0; id <= 8; id++) { // 插入的位置 
            for(int i = 1; i <= 8; i++) { // 插入的数字 
                string w = s.substr(0, id) + char('0' + i) + s.substr(id, s.size() - id); // 最后的结果,s.substr(x, y)是从下标x后面(包括x)的y个字母
                int end = stoll(w); // 同样的,转换,stoll是将w转换为数字
                int gcd = __gcd(end, n);
                if(mx_gcd < gcd || (mx_gcd == gcd && res > end)) { // 按照规则
                    mx_gcd = gcd, res = end; 
                }
            }
        }
    }  while(next_permutation(num, num + 8)); // 全排列函数
    cout << res << endl;
    return 0;
}