top1编程
← 返回题目
题解

[HNOI2002] 营业额统计

1 条题解

  • 0
    @ 2026-10-21 0:58:21

    1. 解题思路

    逐天把营业额加入有序集合,用lower_bound定位不小于当前值的最小历史值,与前驱比较得到最小波动。

    2. 坑点和注意事项

    n≤32767、营业额绝对值≤10^6。首日直接贡献原营业额;重复值贡献0。动态前驱后继用set保证O(log n),普通数组插入会退化O(n²)。

    3. 复杂度

    • 时间复杂度:O(n log n)。
    • 空间复杂度:O(n)。
    /*
    思路:逐天把营业额加入有序集合,用lower_bound定位不小于当前值的最小历史值,与前驱比较得到最小波动。
    关键规则与坑点:n≤32767、营业额绝对值≤10^6。首日直接贡献原营业额;重复值贡献0。动态前驱后继用set保证O(log n),普通数组插入会退化O(n²)。
    时间复杂度:O(n log n)。空间复杂度:O(n)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        set<int> s;
        long long ans = 0;
        for (int i = 0; i < n; i++)
        {
            int x;
            cin >> x;
            if (!i)
                ans = x;
            else
            {
                set<int>::iterator it = s.lower_bound(x);
                long long best = LLONG_MAX;
                if (it != s.end())
                    best = min(best, (long long)*it - x);
                if (it != s.begin())
                {
                    --it;
                    best = min(best, (long long)x - *it);
                }
                ans += best;
            }
            s.insert(x);
        }
        cout << ans << "\n";
    }
    
    • 1