题解:AT_abc476_d [ABC476D] Automat

· · 题解

题目大意

有 x 张 1 元纸币和 y 张 k 元纸币,有 n 种甜品和 m 种饮品,甜品能用任何面值的纸币购买,饮品只能用 k 元纸币购买,找零均使用 1 元纸币。问最多能买多少物品。

思路

首先,无论对于甜品还是饮品,一定先买价格低的。对于甜品来说,先买价格低的一定能买更多数量;对于饮品来说,价格从低到高的饮品所花费的 k 元纸币数量一定是不降的,因此先买价格低的一定不劣。

然后,因为饮品只能使用 k 元纸币,因此一定先买饮品,因为饮品使用 1 元纸币找零,多出来的能继续购买甜品,但是先买甜品所剩下的 k 元纸币可能不够买饮品的。

所以考虑先买饮料,可以枚举购买饮料的个数,设前缀和数组 sum_i 表示前 i 个饮品的价格之和,于是在买 i 个饮品时,剩余的钱为 x+y\times k-sum_i 元。可以用前缀和与二分,求出最多能购买甜品的数量,再加上饮品的数量即为答案。最终答案取最大值即可。

代码

//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define int long long
const int N = 2e5+10;
int n,m,k,x,y,ans;
int a[N],b[N];
int s1[N],cnt[N],sum[N];

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> k;
    cin >> x >> y;
    for (int i = 1;i <= n;i ++) cin >> a[i];
    for (int i = 1;i <= m;i ++) cin >> b[i];
    sort(a+1,a+n+1);
    sort(b+1,b+m+1);
    for (int i = 1;i <= n;i ++) s1[i] = s1[i-1]+a[i];
    for (int i = 1;i <= m;i ++) {
        int now = (int)ceil(b[i]*1.0/k);
        cnt[i] = cnt[i-1]+now;      // 前 i 个饮品总共需要的 k 元纸币数 
        sum[i] = sum[i-1]+b[i];     // 前 i 个饮品的总价格 
    }
    for (int i = 0;i <= m;i ++) {
        if (cnt[i] > y) break;      // 若所需的纸币数已经超过 y 就可以跳出循环 
        int now = x+y*k-sum[i];     // 剩余的钱 
        int pos = upper_bound(s1+1,s1+n+1,now)-s1-1;    // 求剩余的钱最多能买多少甜品 
        ans = max(ans,pos+i);
    }
    cout << ans;
    return 0;
}