跳到正文

题解

CF1671C Dolce Vita 题解

OIerr约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
CF1671C

版本

  1. v1当前

解题思路

假设预算 xx 能够在每家商店都买一包糖,那么每天就可以买 nn 包,直到有一天每家商店的价格之和超过 xx 了,那么根据贪心的思想,我们不买最贵的那家,选择剩下的 n−1n-1 家,这样每天就能买 n−1n-1 包,直到 n−1n-1 家商店的价格之和也超过 xx,以此类推。

那么我们先将每家商店的初始价格从大到小排好序,设 days[i]\text{days}[i] 表示除去前 i−1i-1 家商店,每天购买第 ii 到 nn 家商店的 n−i+1n-i+1 包糖最多能买到第几天而不会超过预算 xx。

因此在 1∼days[1]1 \sim \text{days}[1] 天每天能购买 nn 包糖,在 days[1]∼days[2]\text{days}[1] \sim \text{days}[2] 天每天能购买 n−1n-1 包糖,以此类推,即 res=days[1]×n+(days[2]−days[1])×(n−1)+⋯+(days[n]−days[n−1])\text{res} = \text{days}[1] \times n + (\text{days}[2] - \text{days}[1]) \times (n-1) + \cdots + (\text{days}[n] - \text{days}[n-1])。

Code

C++
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

typedef long long LL;
const int N = 200010;
int a[N], days[N];
int n, x;

int main()
{
    int T;
    cin >> T;
    while (T--)
    {
        cin >> n >> x;
        LL sum = 0, res = 0;
        for (int i = 0; i < n; i++) cin >> a[i], sum += a[i];
        sort(a, a + n, greater<int>());
        for (int i = 0; i < n; i++)
        {
            if (sum > x) days[i] = 0;
            else days[i] = (x - sum) / (n - i) + 1;
            sum -= a[i];
        }
        for (int i = 0; i < n; i++)
        {
            if (!i) res += days[i] * n;
            else res += (days[i] - days[i - 1]) * (n - i);
        }
        cout << res << endl;
    }
    return 0;
}
原文