1 solutions

  • 0
    @ 2025-5-28 19:14:02

    注意到一定是购买按照排序后前一半,以后一半售出最佳,如果一共有偶数件,直接按照一半一半的购买即可,但是如果是奇数件,需要从前往后买 n/2n/2 向下取整,从后往前卖n/2n/2 向下取整,会空出中间一个。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    #define int long long
    
    using namespace std;
    
    typedef pair<int, int> PII;
    
    void solve()
    {
        int n;
        cin >> n;
        vector<PII> a(n);
        for (int i = 0; i < n; i++) cin >> a[i].first >> a[i].second;
        sort(a.begin(), a.end());
        int sum = 0;
        for (auto t : a) sum += t.second;
        int cnt = sum / 2;
        int sum1 = 0, sum2 = 0;
        for (auto t : a)
        {
            if (t.second <= cnt)
            {
                sum1 += t.first * t.second;
                cnt -= t.second;
            }
            else if (cnt > 0)
            {
                sum1 += cnt * t.first;
                cnt = 0;
                break;
            }
        }
        cnt = sum / 2;
        for (int i = n - 1; i >= 0; i--)
        {
            if (a[i].second <= cnt)
            {
                sum2 += a[i].first * a[i].second;
                cnt -= a[i].second;
            }
            else if (cnt > 0)
            {
                sum2 += cnt * a[i].first;
                cnt = 0;
                break;
            }
        }
        cout << sum2 - sum1 << '\n';
    }
    
    signed main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0), cout.tie(0);
    
        int t = 1;
        while (t--)
        {
            solve();
        }
    }
    
    • 1

    Information

    ID
    1488
    Time
    1000ms
    Memory
    512MiB
    Difficulty
    7
    Tags
    (None)
    # Submissions
    97
    Accepted
    19
    Uploaded By