一、题意: 有n个应用程序,每个应用程序占用a[i]个内存,便利点为b[i],每删除一个应用程序会释放a[i]个内存,损失b[i]个便利点,问需要释放至少m个内存所损失的便利点最少为多少,若不存在则输出-1。
二、思路: 因为便利点只有1和2,所以我们可以将便利点为1和便利点为2的程序分开为两个数组a1,a2,然后分别按照内存从大到小排序。
然后对a2做前缀和处理,遍历a1,然后用二分查找的方式在前缀和中找到符合pre[i]>=m-a1的位置,计算所需的便利点。
代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#define int long long
using namespace std;
const int inf = 1e9 + 7;
int a[200005],b[200005];
int a1[200005], a2[200005];
int pre[200005];
int cmp(int x, int y) {
return x > y;
}
signed main()
{
int t;
scanf("%lld", &t);
while (t--) {
int n, m;
scanf("%lld%lld", &n, &m);
int ans = inf, cnt = 0;
int len1 = 0, len2 = 0;
for (int i = 1; i <= n; i++) { scanf("%lld", &a[i]); }
for (int i = 1; i <= n; i++) {
scanf("%lld", &b[i]);
if (b[i] == 1)a1[++len1] = a[i];
else a2[++len2] = a[i];
}
sort(a2+1, a2 + 1+len2, cmp);
sort(a1 + 1, a1 + 1 + len1, cmp);
for (int i = 1; i <= len2; i++)pre[i] = pre[i - 1] + a2[i];
for (int i = 1; i <= len1; i++) {
cnt += a1[i];
if (cnt >= m) { ans = min(ans, i); break; }
int x = m - cnt;
int p = lower_bound(pre + 1, pre + 1 + len2, x) - pre;
if (p == len2 + 1)continue;
ans = min(ans, i + p * 2);
}
int p = lower_bound(pre + 1, pre + 1 + len2, m) - pre;
if (p != len2 + 1)
ans = min(ans, p * 2);
if (ans == inf)printf("-1\n");
else
printf("%lld\n", ans);
}
return 0;
}