1 条题解

  • 0
    @ 2026-10-26 23:48:27

    思路与算法

    七段数字每位需2至7根,因此先把位数定为ceil(n/7),从高位起枚举最小数字(首位排除0),仅当剩余木棍能由剩余位数消耗2..7根时接受。

    正确性说明

    除n=1外,ceil(n/7)位的总消耗区间包含n,每位2..7均有一个数字实现且首位非零同样覆盖2..7,所以最少位数可行。固定最少位数时,剩余d位能凑的耗材恰为[2d,7d]全部整数,贪心挑最小可延续数字不会失去可行最优,逐位得到最小正整数。

    复杂度

    O(n)输出线性时间、O(1)额外状态空间,输入T组串行;每位最多试10个数字。

    易错点

    0不是正整数且首位不能0;n=1无解。排版负号‐1与半角-1同为无解,本地评测兼容两种负号,正数保持无前导零。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int T;
        cin >> T;
        int cost[] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
        while (T--) {
            int n;
            cin >> n;
            if (n == 1) {
                cout << "-1\n";
                continue;
            }
            int len = (n + 6) / 7;
            for (int i = 0; i < len; i++) {
                int rest = len - i - 1;
                for (int d = i == 0 ? 1 : 0; d <= 9; d++)
                    if (n - cost[d] >= 2 * rest && n - cost[d] <= 7 * rest) {
                        cout << d;
                        n -= cost[d];
                        break;
                    }
            }
            cout << "\n";
        }
    }
    
    • 1

    【24CSPJ普及组】小木棍(sticks)

    信息

    ID
    1941
    时间
    1000ms
    内存
    128MiB
    难度
    普及−
    标签
    递交数
    0
    已通过
    0
    上传者