top1编程
← 返回题目
题解

[NOIP 2008 提高组] 火柴棒等式

1 条题解

  • 0
    @ 2026-10-20 23:51:04

    1. 解题思路

    预计算数字的火柴数,按火柴数排序候选加数,再枚举A、B并检查cost[A]+cost[B]+cost[A+B]+4等于n。

    **关键规则:**0需要6根;加号和等号共4根;A、B有序,交换后通常是不同等式。

    2. 坑点和注意事项

    • 数据范围:n≤24,U=10000。
    • 0需要6根;加号和等号共4根;A、B有序,交换后通常是不同等式。
    • 保留原源码的剪枝与候选上界;加数若有五位则本身至少10根,和也至少10根,另一个数至少2根,再加4根超过24,因此A、B最多四位。关键数字图尚须核对。

    3. 复杂度

    • **时间复杂度:**O(U² + U log U)。
    • **空间复杂度:**O(U)。
    /*
    思路:预计算数字的火柴数,按火柴数排序候选加数,再枚举A、B并检查cost[A]+cost[B]+cost[A+B]+4等于n。
    关键规则:0需要6根;加号和等号共4根;A、B有序,交换后通常是不同等式。
    数据范围:n≤24,U=10000;注意数组下标和中间运算的数据类型。
    时间复杂度:O(U² + U log U);空间复杂度:O(U)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int cost[20000];
    bool cmp(int x, int y)
    {
        return cost[x] < cost[y];
    }
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        int digit[] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
        // [NOIP 2008 提高组] 火柴棒等式:0需要6根;加号和等号共4根;A、B有序,交换后通常是不同等式。
        for (int i = 0; i < 20000; i++)
        {
            cost[i] = 0;
            if (!i)
                cost[i] = 6;
            for (int x = i; x; x /= 10)
                cost[i] += digit[x % 10];
        }
        int a[10000];
        for (int i = 0; i < 10000; i++)
            a[i] = i;
        sort(a, a + 10000, cmp);
        int ans = 0;
        for (int i = 0; i < 10000; i++)
        {
            int x = a[i];
            if (cost[x] + 4 + 4 > n)
                break;
            for (int j = 0; j < 10000; j++)
            {
                int y = a[j];
                if (cost[x] + cost[y] + 6 > n)
                    break;
                ans += cost[x] + cost[y] + cost[x + y] + 4 == n;
            }
        }
        cout << ans << '\n';
    }
    
    • 1